Smooth scrolling

      No Comments on 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:

(selector).animate({styles},speed,easing,callback)

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:

<script>
$("a").on('click', function(event){
 
 // prevents browser's default scroll function
 event.preventDefault();

 //animate function 
    $('html, body').animate({
        scrollTop: $(this.hash).offset().top
      }, 800, function(){
   
     // to add "#" to url  after scroll
                 window.location.hash = hash;
    });
});
</script>
<body>
 <a href="#scanfcode_section1">Scroll to section one</a>
 <div class="main_scroll">
 </div>
 <div class="main_scroll" id="scanfcode_section1">
 </div>

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

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

Leave a Reply

Your email address will not be published. Required fields are marked *