Detect ID in anchor and scroll to it

There are many times when you will have in your menu some links that are pointing to elements within your page and you need a way to detect witch are those links and auto-scroll to that content in a cool manner.
First step is finding those links that are pointing to an id on the page and that can be achieved with a click action on the a[href*=#]:not([href=#]) that means get all anchors that contain an href but exclude anchors with an href value that only has an # within.
Then we get just the id from the hash and check if that element exists on the page target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length).
If it exist then we do the scroll animation to it and we prevent the default on the anchor click.
$('a[href*=#]:not([href=#])').click(function(e) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top
    }, 1000);
    return false;
  }
});

Result Box
  • html
  • css
  • js

Share This:

Feel free to leave a comment!

You might alos be interested in: