jQuery smooth scroll to id

Here’s a script that you can use to allow smooth-scrolling to sections on your website by assigning ids to them and then hash-linking to the ids.

As a demo, click on this link to smooth-scroll down to the comments section. Don’t forget to scroll back up here. 🙂

<!-- jquery smooth scroll to id's -->  
<script>
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 500);
        return false;
      }
    }
  });
});
</script>

Where to place it

If you’re using WordPress, insert the code in your child theme‘s footer.php file right before the closing body tag </body>.

If you have no access to the theme files, you can embed the code right inside the post/page editor (you must be editing the post in Text mode) or on a Text widget that will load up on all pages.

If you’re using any other CMS or just HTML, you can insert the code in a section that loads up on all pages right before the closing body tag </body>.

How to use

In the links you’re creating, simply use the hash symbol # along with the target element’s id.

In the demo, the link was <a href="#comments">this link</a> and the target element (comments section) was <div id="comments">…</div>

Hope this worked for you as well. If you have questions, encounter issues or have an alternative solution, let me know in the comments section down below.

Published by

Bibiano Wenceslao

Father of one. Works from home. Interested about UX, social media, web trends, customer service, workflow automation, technology and life.

14 thoughts on “jQuery smooth scroll to id”

  1. hi mate
    thanks for your amazing post
    i just have one problem when i click page scrolls perfectly but it dose scroll too much i mean it goes beyond my element like when i use a it goes under my fixed
    i really dono how to explain hope you understand what im saying.

  2. First off, really awesome. I have been looking for a good scroller for a long time now.

    This works really well on desktop browsers, however; on mobile it seems to be a bit slow. I’m not sure if it’s my device or the something with the code. Do you think you could help me out?

    1. Hi – Thanks! Can you detail a bit more about how you accessed the website e.g. device model, mobile browser used, etc.? Everything appears to be OK from my Zenfone 5, but I admittedly haven’t tested this yet with nearly every other device.

  3. Is there a way for it to NOT make the element with the ID go to the top-most of the browser page? This site (http://training.an.edu/_dev/) is in early stages of development. If you click on one of the Government or Corporate links within the box to the left of the video, it moves the entire box to the top of the page. I would like the box to remain in the same place within the browser page and only scroll the content in the DIV next to the links.

    Any ideas?

    1. Hi Stephen – Unfortunately, using the hash symbol in links forces the browser to position the target element at the top edge of the browser window if I’m right. I think I may have encountered an alternative way that could work better on your case but couldn’t remember how it’s called or the search term for it. I’ll let you know if I ever run into it again. Thanks!

  4. This ins’t working on WordPress.
    Log:
    JQMIGRATE: Migrate is installed, version 1.4.1
    VM548:250 Uncaught TypeError: $ is not a function
    at VM548:250

    1. Ok, i found solution.
      For WordPress, code must looks that:

      jQuery(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;
      }
      });
      });

Leave a Reply