Web development basics Web development snippets

Smooth scrolling

Smooth scrolling is used to scroll a web page to particular section smoothly.Without smooth scrolling, browser would abruptly scroll to the section as specified in the bookmark link.Smooth scrolling of links is applied to bookmark links.

Smooth scrolling

Adding smooth scroll

Smooth scroll are added using jQuery’s animate() function. By definition animate() function performs custom animation on set of CSS properties.Only numerical methods can be updated using animate() function.

Syntax:

Here selector are id, class or tag names used to animate. Style are required. They are the CSS properties that would be affected.

For applying smooth scroll, use this:

Let’s understand this code

Sometimes the browsers have already a code snippet for smooth scroll or say only scroll. To overwrite the function, such that browser code (default) does not hold we use event.preventDefault();.
Next is the jQuery animate() function with selectors being html ,body. The scrollTop property sets or returns the number of pixels an element’s content is scrolled vertically. scrollTop property is the style part in the syntax of animate function.

$(this.hash).offset().top is the value assigned to scrollTop property.this.hash selects the elements with id attribute matching the hash “#” value of the link clicked. For example: #scanfcode_section1.

offset() returns the offset coordinates of selected elements relative to the document. offset().top will return offset coordinates of selected elements from the top.

Include jQuery library


Example:

See the Pen Smooth scroll by scanfcode (@scanfcode) on CodePen.

Summary
Smooth scrolling
Article Name
Smooth scrolling
Description
Smooth scrolling is used to scroll a web page to particular section smoothly.Without smooth scrolling, browser would abruptly scroll to the section as specified in the bookmark link.Smooth scrolling of links is applied to bookmark links.
Author
Publisher Name
Scanfcode
Publisher Logo