Open In App

How to set smooth scroll after clicking the link using JavaScript ?

Last Updated : 14 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

There are two methods to smoothly scroll a web page after clicking the anchor link which are discussed below:

Method 1: Using scrollIntoView() with the ‘smooth’ behavior: The scrollIntoView() method is used to scroll the view of the user to the element that it is called upon. It contains several options that may be defined to modify the scroll behavior. One of these is ‘behavior’ property. The default value of this property makes the scroll instantly jump to its destination, instead of smoothly scrolling. Setting this value to ‘smooth’ changes this behavior and makes the page scroll smoothly.

The hash portion of the anchor link is first extracted using the hash property and it is selected with the querySelector() method. The scrollIntoView() method is then called on this selected element to smoothly scroll the page to this location.

Example: 

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>
        How to set smooth scrolling after
        clicking an anchor link using
        JavaScript?
    </title>
 
    <style>
        .scroll {
            height: 1000px;
            background-color: lightgreen;
        }
    </style>
</head>
 
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
     
    <b>
        How to set smooth scrolling after
        clicking an anchor link using
        JavaScript?
    </b>
     
    <p id="dest">
        Click on the button below to
        scroll to the top of the page.
    </p>
 
     
    <p class="scroll">
        GeeksforGeeks is a computer science
        portal. This is a large scrollable
        area.
    </p>
 
     
    <a href="#dest">
        Scroll to top
    </a>
     
    <script>
        // Define selector for selecting
        // anchor links with the hash
        let anchorSelector = 'a[href^="#"]';
     
        // Collect all such anchor links
        let anchorList =
            document.querySelectorAll(anchorSelector);
         
        // Iterate through each of the links
        anchorList.forEach(link => {
            link.onclick = function (e) {
     
                // Prevent scrolling if the
                // hash value is blank
                e.preventDefault();
         
                // Get the destination to scroll to
                // using the hash property
                let destination =
                    document.querySelector(this.hash);
         
                // Scroll to the destination using
                // scrollIntoView method
                destination.scrollIntoView({
                    behavior: 'smooth'
                });
            }
        });
    </script>
</body>
 
</html>


Output: 

scroll-behavior

Method 2: Using jQuery scrollTop() method: The scrollTop() method in jQuery is used to scroll to a particular portion of the page. Animating this method with the available inbuilt animations can make the scroll smoother.

The hash portion of the anchor link is first extracted using the hash property and its position on the page is found out using the offset() method. The scrollTop() method is then called on this hash value to scroll to that location. This method is animated by enclosing it within the animate() method and specifying the duration of the animation to be used in milliseconds. A larger value would make the animation slower to complete than a smaller value. This will smoothly animate all the anchor links on the page when they are clicked.

Example:  

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>
        How to set smooth scrolling after
        clicking an anchor link using
        JavaScript?
    </title>
     
    <script src=
    </script>
     
    <style>
        .scroll {
            height: 1000px;
            background-color: lightgreen;
        }
    </style>
</head>
 
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
 
    <b>
        How to set smooth scrolling after
        clicking an anchor link using
        JavaScript?
    </b>
     
    <p id="dest">
        Click on the button below to
        scroll to the top of the page.
    </p>
 
     
    <p class="scroll">
        GeeksforGeeks is a computer science
        portal. This is a large scrollable
        area.
    </p>
 
     
    <a href="#dest">
        Scroll to top
    </a>
     
    <script>
         
        // Define selector for selecting
        // anchor links with the hash
        let anchorSelector = 'a[href^="#"]';
     
        $(anchorSelector).on('click', function (e) {
         
            // Prevent scrolling if the
            // hash value is blank
            e.preventDefault();
     
            // Get the destination to scroll to
            // using the hash property
            let destination = $(this.hash);
     
            // Get the position of the destination
            // using the coordinates returned by
            // offset() method
            let scrollPosition
                = destination.offset().top;
     
            // Specify animation duration
            let animationDuration = 500;
     
            // Animate the html/body with
            // the scrollTop() method
            $('html, body').animate({
                scrollTop: scrollPosition
            }, animationDuration);
        });
    </script>
</body>
 
</html>


Output: 

jquery-animate

 



Similar Reads

Open a link without clicking on it using JavaScript
Problem Statement: How to open a link without clicking on it using JavaScript? Solution: The link will be open when the mouse moves over the text. It returns a newly created window, or NULL if the call gets failed. Syntax: window.open( URL, name, Specs ) Parameters: This function accepts three parameters as mentioned above and described below: URL:
2 min read
How to display confirmation dialog when clicking an &lt;a&gt; link using JavaScript / jQuery ?
Given &lt;a&gt; element and the task is to display the confirmation message when clicking the &lt;a&gt; link, with the help of JavaScript and jQuery. Display confirmation dialog when clicking an &lt;a&gt; link using JavaScript onclick Event: This event occurs when the user clicks on an element. Syntax: In HTML: &lt;element onclick="myScript"&gt; In
5 min read
How to submit a form by clicking a link in JavaScript ?
In this article, we are going to learn how to submit a form by clicking a link in JavaScript. ApproachHTML Structure:Basic HTML structure with a title, heading, and a form to submit details.The form contains input fields for Name, Age, and City.JavaScript Function:submitForm() function triggered by clicking "Submit Here."Retrieves the form by its I
2 min read
Foundation CSS Smooth Scroll
Foundation CSS is an open-source &amp; responsive front-end framework built by ZURB foundation in September 2011, that makes it easy to design beautiful responsive websites, apps, and emails that look amazing &amp; can be accessible to any device. It is used by many companies such as Facebook, eBay, Mozilla, Adobe, and even Disney. The framework is
5 min read
Foundation CSS Smooth Scroll Installation
Foundation CSS is an open-source and responsive front-end framework built by the ZURB foundation in September 2011, that makes it easy to layout stunning responsive websites, apps, and emails that appear amazing and can be accessible to any device. For setup/installation of the Smooth Scroll in our code just add the attribute data-smooth-scroll to
3 min read
How to change the background color after clicking the button in JavaScript ?
In this article, we will learn how we can change the background color of an element once a button is clicked by the user using JavaScript and jQuery. Table of Content Using JavaScript to change the backgroundUsing jQuery to change the backgroundUsing JavaScript to change the backgroundThis approach uses JavaScript to change the background-color aft
2 min read
How to change the button color after clicking it using AngularJS ?
Created an HTML button and the task is to change the background color of the button when pressing it with the help of AngularJS. This task can be accomplished using the ng-click directive that helps to toggle the display of the content when the button or any specific HTML element is clicked. Here, the ng-controller directive is applied to add the c
2 min read
Hide scroll bar, but while still being able to scroll using CSS
To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below: -webkit- (Chrome, Safari, newer versions of Opera): .element::-webkit-scrollbar { width: 0 !important } -moz- (Firefox): .element { overflow: -mo
3 min read
Sound generation on clicking the button using JavaScript
The sound generation after clicking the button, receiving notifications or at the time of page load can be done by using JavaScript. Note: URL provided in the playSound function can be changed to give the custom sound url. Style property is not the part of implementation. It is used to provide a nice interface for viewers. Example: This example gen
1 min read
How to send row data when clicking button using JavaScript ?
To send row data when clicking a button using JavaScript, you can follow a straightforward approach by associating the button with the corresponding row data. Approach:HTML Structure:The HTML file contains a table with columns for Name, Email, and an Action button in each row. Each &lt;tr&gt; element has data-name and data-email attributes to store
2 min read