Quantcast
Viewing all articles
Browse latest Browse all 15

Smooth Scrolling jQuery Snippet

I just wanted to share a simple jQuery script that I found on CSS Tricks that animates the scrolling to an element that is on the same page. Simple add this to your javascript file – be sure you have a reference to the jQuery library on your site if you do not already.

$(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
        }, 1000);
        return false;
      }
    }
  });
});

To adjust the scroll speed, simply replace the 1000 (highlighted in red text) to a smaller number for a faster scroll or a larger number for a slower scroll.

This script can be used like any anchor tag: the link <a href="#mydiv">My Div</a> can be used to scroll to the element <div id="mydiv"></div>

The post Smooth Scrolling jQuery Snippet appeared first on Local Wisdom.


Viewing all articles
Browse latest Browse all 15

Trending Articles