Open In App

How to scroll the page up or down using anchor element in jQuery ?

The problem is to include a slide effect whenever we click a local anchor and we want to scroll up or down the page accordingly. Earlier we can do it natively by using CSS property.

Syntax:



a {
  scroll-behavior: smooth;
}

Now with the help of jQuery, we can do it by using the following two methods:

Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to scroll the page up or down
        using anchor element in jQuery ?
    </title>
  
    <script src=
    </script>
  
    <script>
        $(document).ready(function () {
  
            // Add smooth scrolling to all links
            $("a").on('click', function (event) {
  
                // Make sure this.hash has a value
                // before overriding default behavior
                if (this.hash !== "") {
  
                    // Prevent default anchor
                    // click behavior
                    event.preventDefault();
  
                    // Store hash
                    var hash = this.hash;
  
                    // Using jQuery's animate() method 
                    // to add smooth page scroll
                    // The optional number (800) specifies
                    // the number of milliseconds it takes
                    // to scroll to the specified area
                    $('html, body').animate({
                        scrollTop: $(hash).offset().top
                    }, 500, function () {
  
                        // Add hash (#) to URL when done 
                        // scrolling (default click behavior)
                        window.location.hash = hash;
                    });
                } // End if
            });
        });
    </script>
  
    <style>
        body,
        html, .primary {
            height: 150%;
        }
  
        section {
            min-height: 150%;
        }
    </style>
</head>
  
<body>
    <div>
        <a href="#section1">
            Click Me to Smooth Scroll
            to Section 1 Below
        </a>
    </div>
    <div>
        <a href="#section2">
            Click Me to Smooth Scroll
            to Section 2 Below
        </a>
    </div>
    <div>
        <a href="#section3">
            Click Me to Smooth Scroll
            to Section 3 Below
        </a>
    </div>
  
    <div class="primary">
        <section></section>
    </div>
      
    <div class="primary" id="section1">
        <section style="background-color:cyan"></section>
    </div>
      
    <div class="primary" id="section2">
        <section style="background-color:yellow"></section>
    </div>
      
    <div class="primary" id="section3">
        <section style="background-color:red"></section>
    </div>
</body>
  
</html>

Output:




Article Tags :