Improved Animated Scrolling Script for Same-Page Links

After posting the last entry on animated scrolling with jQuery 1.2, I realized that I had left out an important piece of code. Actually, I didn't discover it until someone notified me that another page on the site was broken. Can you spot the problem(s)? [Note: the problem is not in line 3. The syntax highlighter just can't handle the regular expression with two slashes in it ("//") and is incorrectly treating them as a comment mark.] See the answer below the code.

JavaScript:
  1. $(document).ready(function(){
  2.   $('a[href*=#]').click(function() {
  3.     if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
  4.     && location.hostname == this.hostname) {
  5.       var $target = $(this.hash);
  6.       $target = $target.length && $target
  7.       || $('[name=' + this.hash.slice(1) +']');
  8.       if ($target.length) {
  9.         var targetOffset = $target.offset().top;
  10.         $('html,body')
  11.         .animate({scrollTop: targetOffset}, 1000);
  12.        return false;
  13.       }
  14.     }
  15.   });
  16. });

Answer: The animated scrolling script hijacks links that look like this: <a href="#">. A couple people confirmed in the comments that the script needed a bit more work, so I figured we could take one more pass at it.

By the way, even though we attached the click event handler to all links that have the "#" symbol anywhere in the href, the very next line ensures that the link is pointing to the same page — by checking for a match between location.pathname and this.pathname — and the line after that ensures that it's pointing to the same domain, by checking for a match between location.hostname and this.hostname. With this approach, we can accommodate same-page links whether they include a fully-qualified URL, a relative URL, or just the fragment identifier.

Check for the Hash

Let's fix the problem with the <a href="#"> links. The first thing we have to do is see if there is actually something following the "#" symbol in the href. Apparently, if there is a lone "#" symbol, without any following characters, Firefox and Internet Explorer don't consider it a hash. Safari does, however. So, to avoid a false positive on <a href="#">, we need to first strip the "#" and then check if there is anything left. We can do so by adding this condition to the first if statement: && this.hash.replace(/#/,'')

Check for the Named Anchor

Since we're already changing the script, maybe it's a good time to make some of it more readable, too. This part with the "short-circuit" logic, using && and ||, makes me a little dizzy:

JavaScript:
  1. var $target = $(this.hash);
  2. $target = $target.length && $target
  3. || $('[name=' + this.hash.slice(1) +']');
  4. if ($target.length) {

There is absolutely nothing wrong with this syntax. In fact, more advanced JavaScripters use it all the time. But I feel more comfortable using a simpler, more straightforward style. So, let's set two variables — one for a target ID and one for a target named anchor. We'll then use conditional (aka ternary) operators to set a third, $target, variable as the target ID if it's there, and if not, the target named anchor if it's there, and if not, false. Then we can just check if $target has some value (other than false):

JavaScript:
  1. var $targetId = $(this.hash),
  2.   $targetAnchor = $('[name=' + this.hash.slice(1) +']');
  3. var $target = $targetId.length ? $targetId
  4.   : $targetAnchor.length ? $targetAnchor
  5.     : false;
  6. if ($target) {

Now it appears that the animated scrolling behavior will be attached to all same-page links and not break other stuff on the page.

Loop First, Bind Last

But there is another problem. Since we're still binding the .click() method to every link with "#" in it, even if it's appropriately avoiding applying the animation for some of those links, jQuery is still hijacking links that have an inline onclick handler (but, oddly, only the first time those links are clicked). To fix this problem, we can replace the .click() with .each(). Then we'll iterate through all links that have "#" somewhere in them, but place the conditions inside the loop so that we bind the click handler only after we've filtered out all the links that don't apply. Here is what the script looks like with the change:

JavaScript:
  1. $(document).ready(function() {
  2.   $('a[href*=#]').each(function() {
  3.     if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
  4.     && location.hostname == this.hostname
  5.     && this.hash.replace(/#/,'') ) {
  6.       var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
  7.       var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
  8.        if ($target) {
  9.          var targetOffset = $target.offset().top;
  10.          $(this).click(function() {
  11.            $('html, body').animate({scrollTop: targetOffset}, 400);
  12.            return false;
  13.          });
  14.       }
  15.     }
  16.   });
  17. });

Notice especially lines 2 and line 10. This change not only takes care of our problem, but it feels cleaner somehow, too. Is it more efficient? I don't know. Maybe someone else can tell us in the comments.

Normalize Directory Indexes

To be complete, we should probably take care of one more thing: the possibility that, on an "index" page, a link could point to "/path/index.htm" when the current location says "/path/" or vice versa. One way to "normalize" these index pages and links is to add a couple more .replace() methods to both sides of the equation in line 3.

Update

Aman suggested in a comment below that I make this process DRYer, and kangax provided a great example. So we can write a filter function and apply it to both sides rather than repeating the three replaces on each side:

JavaScript:
  1. function filterPath(string) {
  2.   return string
  3.     .replace(/^\//,'') 
  4.     .replace(/(index|default).[a-zA-Z]{3,4}$/,'')  // first additional replace
  5.     .replace(/\/$/,'')// second additional replace
  6. }

The first additional .replace() will find a string represented by "index" or "default," followed by a dot, followed by any three or four letters at the end the pathname, and replace it with an empty string (i.e. remove it). The second one will replace a trailing slash with an empty string. As with chained jQuery methods, these regular-expression methods can be placed on separate lines to improve readability. Finally, we have a bullet-proof (I hope) animated scrolling script for same-page links:

JavaScript:
  1. $(document).ready(function() {
  2.   function filterPath(string) {
  3.     return string
  4.       .replace(/^\//,'') 
  5.       .replace(/(index|default).[a-zA-Z]{3,4}$/,'') 
  6.       .replace(/\/$/,'');
  7.   }
  8.   $('a[href*=#]').each(function() {
  9.     if ( filterPath(location.pathname) == filterPath(this.pathname)
  10.     && location.hostname == this.hostname
  11.     && this.hash.replace(/#/,'') ) {
  12.       var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
  13.       var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
  14.        if ($target) {
  15.          var targetOffset = $target.offset().top;
  16.          $(this).click(function() {
  17.            $('html, body').animate({scrollTop: targetOffset}, 400);
  18.            return false;
  19.          });
  20.       }
  21.     }
  22.   });
  23. });

If you try it out, let me know how it goes.

Update 2

Ariel Flesler has written an excellent ScrollTo plugin, which he says was inspired by this blog entry. Be sure to check out the demo.

31 Responses to “Improved Animated Scrolling Script for Same-Page Links”

  1. Aman Gupta Says:

    Lines 4-6 are the same as lines 8-10. Surely there's a DRYer solution?

  2. Karl Says:

    Hi Aman,

    I'm not sure if there is a DRYer solution, because both location.pathname and this.pathname need to be run through the three replace methods in order to account for the possibility on an "index" page that the current URL and the link's href are represented differently: with or without a file name, such as index.html, and with or without the trailing slash. The first replace accounts for browser differences in including an initial slash in the pathname.

    Also, as I imply in the entry, lines 3 - 10 can be written on a single line, so maybe it just looks like more is going on than there actually is. If you can think of something DRYer and better, though, please let me know. I'm always eager to learn.

  3. Learning jQuery » Animated Scrolling for Same-Page Links Says:

    [...] I've posted a new entry about how to achieve the same effect (and more) using jQuery 1.2, without the need for any of the Interface plugin modules: Animated Scrolling with jQuery 1.2. [Posted an improved version Oct. 20, 2007] [...]

  4. napyfab:blog» Blog Archive » links for 2007-10-21 Says:

    [...] Learning jQuery » Improved Animated Scrolling Script for Same-Page Links (tags: jquery scroll scrolling animation animated javascript webdev webdesign web development design) [...]

  5. Marcus T Says:

    Great stuff! However, it's surprising you didn't provide an optional parameter to specify an easing algorithm other than the default linear. I've added it myself but perhaps you might want to do the same to your code published above.

  6. Karl Says:

    Hi Marcus,

    Sorry about that. It's really easy to use easing with the .animate() method. Just include an easing plugin and then add in the easing type as a parameter to .animate(). Something like this:

    $('html, body').animate(
      {scrollTop: targetOffset},
      {duration: 400, easing: 'easeInOutExpo'}
    );

    You can also do the same thing with slightly different syntax, like this:

    $('html, body').animate(
      {scrollTop: targetOffset}, 400, 'easeInOutExpo'
    );
  7. Ariel Flesler Says:

    Verrrry good to Karl.. I don't know if you saw, but I made a plugin, inspired on your post. To scroll the window and overflowed elements as well... I pulled out an implementation of your "same-page-links-scrolling" using the plugin as someone asked for that. I must say all the credit goes to you ;)

  8. Ariel Flesler Says:

    You could make the replacement to the page URI once and store it in a variable, then use jQuery.fn.filter with a function, and only to those passing the filter, apply the click. I think that might look cleaner.

  9. kangax Says:

    I might be failing to see something, but what's up with this "replace" repetition?

    Why not define a helper "filter" function to keep it "DRY" as Aman pointed out.

    
    $(document).ready(function() {
       function filter(string) {
          return string
             .replace(/^\//,'')
             .replace(/(index|default)\.[a-zA-Z]{3,4}$/,'')
             .replace(/\/$/,'')
       }
       $('a[href*=#]').each(function() {
          if (filter(location.pathname) == filter(this.pathname)
             && location.hostname == this.hostname
    	 && this.hash.replace(/#/,'') ) {
    	    var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
    	    var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
    	    if ($target) {
    	       var targetOffset = $target.offset().top;
    	       $(this).click(function() {
    	          $('html, body').animate({scrollTop: targetOffset}, 400);
    	          return false;
    	        });
                }
             }
          });
       });
    
    
  10. Karl Says:

    Thanks a lot, Kangax! That makes a lot of sense. I'll update the entry to include your function.

  11. Ariel Flesler Says:

    I added this snippet of code, and it worked fine in IE and FF.

    function samePage( link ){
    return location.href.replace(location.hash,'') == link.href.replace(link.hash,'');
    };

    return true or false.

  12. Matthew Moore Says:

    Hi,

    I've read all your posts relating to scrolling and I understand how it can scroll the page within the browser but I was wondering is there a way to modify it so that I can present a list of links above a "div" section that has an overflow set to scroll and animate the scrolling of this div?

    Thanks in Advance.

  13. Karl Says:

    Hi Matthew,

    Here is the code I demonstrated in the previous animated-scrolling tutorial. It triggers the scrolling from a single button to a specified place within the scrollable element, but changing it to a list o links triggering a scroll to multiple places within the div should be trivial.

    $(document).ready(function() {
      $('#scrollit').click(function() {
        var divOffset = $('#scrollable').offset().top;
        var pOffset = $('#scrollable p:eq(2)').offset().top;
        var pScroll = pOffset - divOffset;
        $('#scrollable').animate({scrollTop: '+=' + pScroll + 'px'}, 1000, 'bounceout');
      });
    });

    Note, you'll need to use an easing plugin with this example. If you'd rather not have an easing effect, just remove , 'bounceout' from the sixth line.

  14. Matthew Moore Says:

    Follow up to my last post:

    I applied ".parent()" to the click function to animate the div. It works great in FF2 but IE6 put the focus just below the section. Any idea's on how to fix this?

    Also I've pasted the entire code, for your reference, at: http://pastemonkey.org/paste/47261c71-1fa8-4ce9-b09d-2493404fdb0d

    
    <script type="text/javascript" src="/js/jquery/jquery-1.2.1.pack.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
      function filterPath(string) {
    	return string
    	  .replace(/^\//,'')
    	  .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    	  .replace(/\/$/,'');
      }
      $('a[href*=#]').each(function() {
    		if ( (filterPath(location.pathname) == filterPath(this.pathname))
    		&& (location.hostname == this.hostname)
    		&& (this.hash.replace(/#/,'')) ) {
    			var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
    			var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
    			 if ($target) {
    			 var targetOffset = $target.offset().top;
    			 $(this).click(function() {
    				 $target.parent().animate({scrollTop: targetOffset}, 500);
    				 return false;
    			 });
    			}
    		}
      });
    });
    </script>
    
  15. Matthew Moore Says:

    Does this work (in your browsers)?

    
    $(document).ready(function() {
      function filterPath(string) {
    	return string
    	  .replace(/^\//,'')
    	  .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    	  .replace(/\/$/,'');
      }
      $('a[href*=#]').each(function() {
    		if ( (filterPath(location.pathname) == filterPath(this.pathname))
    		&& (location.hostname == this.hostname)
    		&& (this.hash.replace(/#/,'')) ) {
    			var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
    			var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
    			 if ($target) {
    			 var divOffset = $target.parent().offset().top;
    			 var pOffset = $target.offset().top;
    			 var pScroll = pOffset - divOffset;
    			 $(this).click(function() {
    				 $target.parent().animate({scrollTop: pScroll + 'px'}, 500);
    				 return false;
    			 });
    			}
    		}
      });
    });
    

    Full Code at: http://pastemonkey.org/paste/37

  16. Karl Says:

    Yes, it works for me in FF 2 Mac and IE 6 Windows. Try it here: http://test.learningjquery.com/matthew.html

  17. Ariel Flesler Says:

    By the way, I used $('a[hash]') in localScroll and it worked fine in IE, Opera and FF that I tested.
    Seems like href="#" gives empty string as hash, so even better!

  18. Millhouse Says:

    This script works great, thank you for it!

    How could it be modified to show the clicked URL in the address bar?

  19. Karl Says:

    Hi Millhouse,

    Ariel Flesler has taken this script, converted it into a plugin, and improved upon it further. He just announced on the jQuery discussion list that the plugin can now show the clicked URL in the address bar. Take a look.

  20. Cedric Francois Says:

    Cheers mate -works neatly for me...
    Thanks for this and happy xmas.!

  21. Andy Says:

    This gives problems in Opera, using jQuery 1.2.1 and Opera 9.23.
    Some of the links work, other just don't go to the anchor, or got to the absolute top of the page.

    It works well in FF (2 and even 0.7) and IE 7.

  22. Ty (tzmedia) Says:

    Ahhh, Karl, just the man I am looking for...
    Have you seen the buzz around this new teaser site for:
    http://silverbackapp.com/
    The leaves use a parallax scrolling alignment effect when windows width is resized.
    Some parallax backgrounds along with easing effects, would be just killer with this very cutting-edge technique you have going here!!
    Searching the jQ user groups and to my surprise, I couldn't find any discussion at all of parallax scrolling.

  23. seocontest2008 Says:

    me too .. my client wants to work on opera and safari i really dont know why because the percentage of the user who use those browser are very small

  24. Acronyms Says:

    You are not unleashing the power of Jquery

  25. For Web Hosting Says:

    This is nice information though i am looking for css codes to display 5 links in same page. when a user click on these link they don't live that page and comes up the page ins the same page let me know please..

  26. Karl Says:

    Not sure what you mean by "css codes," but to have a link fetch information from another page and update the current page with it (without refreshing), you should look at jQuery's ajax methods. I think you'll find the load() method particularly helpful.

  27. abelafonte Says:

    Is there a way to hilight the selected trigger once your scrolling stops?

  28. Gregory Says:

    i tried to use this script to put a link in my footer to scroll back to the top of the page.
    clicking the link the first time effectively scrolls the page up, however scrolling the page down and clicking the link again has no effect.

    any explanation ?
    thx in advance

  29. Webdesign Says:

    Pretty good idea…

  30. James Says:

    Great work on this script, it's done really elegantly.

    I've got a large site that uses plenty of href="#" for 'back-to-top' links - However, with this updated script it won't animate back to the top without an explicit target id or name.

    Does anyone have any idea how I might get it to work in this scenario?

    James

  31. Trev Says:

    Just wanted to say how good the code is.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <pre> <em> <i> <li> <ol> <strike> <strong> <ul>

IMPORTANT: If you wish to post code examples, please wrap them in <code> tags. Multi-line code should be wrapped in <pre><code> </code></pre> Also, use &lt; instead of < and &gt; instead of > in the examples themselves. Otherwise, you could lose part of the comment when it's submitted.