jQuery Smooth Scroll Howto – Code Sample & Demo

With the jQuery library, you can do a ton of cool things to make a webpage ‘live’. From colours to animations and other special effects, most things are possible. One of these neat things to do is smooth scrolling with jQuery. Ever wondered to see a code example in HTML, CSS and JavaScript for smooth scrolling to a div element in your website webpage?

Example use cases include:

  • smooth scrolling when click on div
  • smooth scroll to top of page HTML
  • smooth scroll to anchor or id

First, you want to include the jQuery library URL. Find it via CDNjs or Google, for example:

https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js

or

https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js

Then, once this line of  programming code is added, copy and paste the following code underneath:

// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $id.offset().top;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});

You now successfully have smooth scrolling on your HTML website or WordPress page!

 

Author Bio

Thank you for your interest in my blog! On this miniblog, I write mostly short (technical) blog posts that might interest other people. Read more about me or feel free to contact me.

 

Leave a Reply

Your e-mail address will not be published. Required fields are marked *