Fixing the jQuery scrollTo bug in Chrome and Safari


Introduction
The jQuery scrollTo plugin provides a smooth scroll effect for navigating within a page. The target to scroll to can be provided in many ways - DOM element (id, class, jQuery element selectors), absolute position, relative position and much more.

A common use of this plugin is to add 'scroll to top' buttons/links on a page. Clicking on these buttons/links would smooth-scoll to the top of the page. The animation effect and its duration can be controlled by setting the appropriate plugin options.

Issue
If the target specified for scrolling is a CSS class/id applied to the HTML body tag, then the smooth-scroll does not work in webkit based browsers like Chrome, Safari and Dolphin (mobile browser).

Solution
Instead of using a CSS class/id associated with the HTML body tag, create a separate HTML element (<div> or <a>) and use its class/id for the scrollTo plugin. This element should be styled appropriately to ensure that it is positioned at the top of the page and its positioning is not affected by other elements and vice versa.

Example
jsFiddle - http://jsfiddle.net/U6gFZ/1/

Code -

<html>
 <head>
  <!-- CSS style to position the placeholder element at the top of the page and making it unobtrusive -->
  <style type='text/css'>
   #top {
    padding: 0px;
    margin: 0px;
    width: 0px;
    height: 0px;
    position: absolute;
    top: 0px;
   }
  </style>
  
  <!-- include jQuery and scrollTo plugin's javascript files -->
  <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'></script>
  <script type='text/javascript' src='http://demos.flesler.com/jquery/scrollTo/js/jquery.scrollTo-min.js'></script>
  
  <!-- initialize the scrollTo plugin on document load -->
  <script type='text/javascript'>
   $(document).ready(function() {    
    $('#scroll-to-top').bind('click', function(e) {
     try {
      e.preventDefault();
      target = this.hash;
      $('html, body').scrollTo(target, 1000); 
     } catch(error) {
      alert('error - '+error);
     }   
      });   
   });
  </script>
 </head>
 
 <body>
  <!-- the placeholder element for top of page -->
  <div id="top"></div>
  
  <!--  add some filler content -->
  <div style='background-color: #FAA; width: 100px; height: 500px; border: #000 solid 1px;'></div>
  <div style='background-color: #AFA; width: 100px; height: 500px; border: #000 solid 1px;'></div>
  <div style='background-color: #AAF; width: 100px; height: 500px; border: #000 solid 1px;'></div>
  
  
  <!-- 'scroll-to-top' link -->
  <a id='scroll-to-top' href='#top'>Go to top</a>
 </body>

</html> 

No comments:

Post a Comment