Monday, August 25, 2014

jQuery: Scroll to #id the easy way

Using links on a page that scroll to certain parts is quite pleasant visually. Previously I have been using this function for the task:

 function scrollToId(id) {  
      $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');  

The links looked like this:

 <a href="javascript://" onclick="scrollToId('#footer');">Footer</a>  

I got a tip from a colleague for an easier way. Using this script at the before the </body> tag, we can turn all links whose href tag starts with a hashtag to a scrolling link automatically...

 <script type="text/javascript">  
      $("document").ready(function() {  
           $('a[href^="#"]').click(function(event) {  
                var target = $( $(this).attr('href') );  
                if( target.length ) {  
                     $('html, body').animate({  
                          scrollTop: target.offset().top  
                     }, 1000);  

The link in this case is simply this:

 <a href="#footer">Footer</a>