Smooth scroll to div using jQuery

Demo

Smooth scrolling using jQuery, gives a better user interface on your web project. Smooth scroll reduces efforts of the users to scroll for reach the certain portion of the page. With smooth scrolling, the user can reach the specific portion of the page by clicking an anchor link.

In this short article, we’ll show how to implement smooth scroll to div using jQuery without manually scroll. Our below script make it very easy and you will be able to implement scroll to an element within a minute.

The following jQuery scroll to div script land you to the specific portion of the page by click on the respective link.

JavaScript

At first include the jQuery library and then write the scroll to div JavaScript.

<script src="jquery.min.js"></script>
<script>
$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
        if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    });
});
<script>

HTML

The href attribute value of the anchor link would be ID name of the div and starting with a hash tag.

<div id="top">
    <a href="#section1">Go Section 1</a>
    <a href="#section2">Go Section 2</a>
</div>
<div id="section1">
    <!-- Content goes here -->
</div>
<div id="section2">
    <a href="#top">BackToTop</a>
    <!-- Content goes here -->
</div>

Related Articles

Comments 0