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.
-
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
-
&& location.hostname == this.hostname) {
-
var $target = $(this.hash);
-
$target = $target.length && $target
-
var targetOffset = $target.offset().top;
-
$('html,body')
-
return false;
-
}
-
}
-
});
-
});
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:
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):
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:
-
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
-
&& location.hostname == this.hostname
-
&& this.hash.replace(/#/,'') ) {
-
if ($target) {
-
var targetOffset = $target.offset().top;
-
return false;
-
});
-
}
-
}
-
});
-
});
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:
-
function filterPath(string) {
-
return string
-
.replace(/^\//,'')
-
.replace(/(index|default).[a-zA-Z]{3,4}$/,'') // first additional replace
-
.replace(/\/$/,''); // second additional replace
-
}
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:
-
function filterPath(string) {
-
return string
-
.replace(/^\//,'')
-
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
-
.replace(/\/$/,'');
-
}
-
if ( filterPath(location.pathname) == filterPath(this.pathname)
-
&& location.hostname == this.hostname
-
&& this.hash.replace(/#/,'') ) {
-
if ($target) {
-
var targetOffset = $target.offset().top;
-
return false;
-
});
-
}
-
}
-
});
-
});
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.



October 20th, 2007 at 4:04 pm
Lines 4-6 are the same as lines 8-10. Surely there's a DRYer solution?
October 20th, 2007 at 4:21 pm
Hi Aman,
I'm not sure if there is a DRYer solution, because both
location.pathnameandthis.pathnameneed 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'shrefare 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.
October 20th, 2007 at 11:05 pm
[...] 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] [...]
October 21st, 2007 at 7:25 pm
[...] Learning jQuery » Improved Animated Scrolling Script for Same-Page Links (tags: jquery scroll scrolling animation animated javascript webdev webdesign web development design) [...]
October 23rd, 2007 at 5:39 am
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.
October 23rd, 2007 at 7:26 pm
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:
You can also do the same thing with slightly different syntax, like this:
October 23rd, 2007 at 8:45 pm
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
October 23rd, 2007 at 8:52 pm
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.
October 25th, 2007 at 10:57 am
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.
October 25th, 2007 at 11:37 am
Thanks a lot, Kangax! That makes a lot of sense. I'll update the entry to include your function.
October 25th, 2007 at 1:24 pm
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.
October 29th, 2007 at 1:08 pm
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.
October 29th, 2007 at 1:19 pm
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.
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.October 29th, 2007 at 1:48 pm
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
October 29th, 2007 at 2:29 pm
Does this work (in your browsers)?
Full Code at: http://pastemonkey.org/paste/37
October 29th, 2007 at 3:08 pm
Yes, it works for me in FF 2 Mac and IE 6 Windows. Try it here: http://test.learningjquery.com/matthew.html
November 9th, 2007 at 9:04 am
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!
November 12th, 2007 at 5:08 pm
This script works great, thank you for it!
How could it be modified to show the clicked URL in the address bar?
November 13th, 2007 at 10:28 am
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.
December 24th, 2007 at 1:24 pm
Cheers mate -works neatly for me...
Thanks for this and happy xmas.!
December 30th, 2007 at 10:04 pm
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.
February 18th, 2008 at 11:39 am
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.
March 1st, 2008 at 11:27 pm
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
April 2nd, 2008 at 7:09 am
You are not unleashing the power of Jquery
May 7th, 2008 at 4:09 am
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..
May 7th, 2008 at 2:06 pm
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.May 18th, 2008 at 3:26 pm
Is there a way to hilight the selected trigger once your scrolling stops?
May 29th, 2008 at 3:55 pm
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
June 2nd, 2008 at 12:12 pm
Pretty good idea…
July 22nd, 2008 at 11:18 am
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
July 24th, 2008 at 3:38 am
Just wanted to say how good the code is.