Code Snippets Gallery
Smooth Scrolling
Performs a smooth page scroll to an anchor on the same page. Hash links only (e.g. href=”#target3″)
Technique #1
<script type="text/javascript">
//Anonymous function that is applied to all internal-links
var jump=function(e)
{
//prevent the "normal" behaviour which would be a "hard" jump
e.preventDefault();
//Get the target
var target = $(this).attr("href");
//perform animated scrolling
$('html,body').animate(
{
//get top-position of target-element and set it as scroll target
scrollTop: $(target).offset().top
//scrolldelay: 2 seconds
},2000,function()
{
//attach the hash (#jumptarget) to the pageurl
location.hash = target;
});
}
$(document).ready(function()
{
$('a[href*=#]').bind("click", jump);
return false;
});
</script>Technique #2
$(function(){
$('a[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) {
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset}, 1000);
return false;
}
}
});
});
Hi,
I cant get this to work. Could you provide the appropiate HTML to go with this Javascript?
Its not obviously clear whats needed, as I’ve tried all sorts of combinations of name values and such.
Any help would be appreciated
:)
There is a Reference URL above with a working example.
D’oh! Didnt see that lol
Will have a go when I get home as I think I’ve spotted where I went wrong.
Thanks :)
I LOVE U!!!! i been tryna find how to do this for months! :-)
works like a charm.. thanks so much.
Thank you so much for this script. Took me awhile, but I got it to work!
The Reference URL is now showing a 404 page. Know anywhere else that has the HTML to go along with the JS? …and preferably in english? :)
Made a new reference URL.
great code, one question,
I have a sidebar widget for my video, archive and tags this code is interfering with. What is the coding/marker to disable this from happening?
You can try to use the jQuery noConflict technique. Read about it here: http://api.jquery.com/jQuery.noConflict/
I cannot get this to work for the life of me, I’m following the example perfectly though… Anyone have any ideas?
Without a description of your problem, or a URL, no one will ever be able to help.
One thing I can say is that make sure you are loading the jquery library.
It’s not working on IE8 at my website, I think there is some kind of Bug…
Could you see it here with IE8? Thank’s
Does this work with Left & Right too?
Just change “top” to “left” ?
Sweet! Thank you
I got the second method working on my site, but I also tried to get the nav container to follow the page by adding it it the code like this
$(‘html,body,#nav’)
So I just added #nav to the selectors here. But it don’t work. The page still scrolls, but the nav container doesn’t follow. Any ideas?
Is the #nav positioned absolute [relative to body] or fixed? That might be the reason.
Work perfectly
Hi Chris, this is awesome! Very simple and clean and works really good.
I was wondering if it is possible to get the hash link in the current URL of the browser window (i.e. http://www.example.com#target3) while keeping the smooth scrolling effect, so the each hash link can be bookmarkable.
Thanks!
Technique #1 let’s you keep the hash links, while Technique #2 does not.
Both examples work great.
I have slightly altered this scroll down to the page onload? My idea here is in PHP to check the refer and only scroll down the page only if they have clicked a link from the domain. At the moment I have
website
Thanks for this Chris! I was trying to do this with Jquery.LocalScroll, this is so much easier!! Saved me a huge headache, thanks.
i have a div with width: 100% height: 100% and another div left: 100% width: 100% so the body is 200%, how can i make the scroll move horizontally?
I changed some bits, which you didn’t explain.. like you expect there to be a corrsponding element id an ID the same as the a.href.. so I changed this
var target = $(this).attr(“href”);
To
var target = $(this).attr(“href”).replace(‘#’,”);
and this
scrollTop: $(target).offset().top
To
scrollTop: $(‘a[name='+target+']‘).offset().top
PS. Keep up the good work.
Hello,
I’m trying to get this to work but for the life of me cant. As far as I am aware, I’ve check the reference and copied exactly… Any help appreciated.
http://www.certohost.com/tutorials.php
Thanks.
Hi,
I used technique #2 and it seems to only work when I click on about, the work and contact link doesn’t seem to work and I don’t know why.
thanks
Awesome, works brilliantly. Barely having to do anything. Thanks Chris
Superb, worked like a charm.
Thanks!
Hello..
Just wondering if you had checked this in Opera… getting some funny results when running some tests… v.nice never the less.
Hi Chris and co.
When I use this method #2, my Firefox Developer Toolbar shows a js error as follows:
Expected identifier or string value in attribute selector but found “#”.
What am I missing..?
To help, I am using jquery-1.4.2.min.js, and I’m linking to h2′s with id’s, like so:
Go to 01
This is Link 01
Thanks in advance.
Sorry, forgot to wrap my code:
<a href="#link-01">Go to 01</a><h2 id="link-01">This is link number 01</h2>Thanks
Jon
works like a charm! thanks a bunch!
Thanks Chris.
This worked perfectly in Firefox and Safari, but not in Opera. I have yet to test out IE. Any fix ideas for Opera. It currently jumps to the #tag, no scroll.
Any know issues and or fixes for IE?
FYI, I used technique #2.
Thanks for the post, i’ve been trying to get something like this working for ages. Any ideas how to alter the scrolling speed?
i used to grab the local scroll for this function. yours works as good. thank you.
Demo Here
http://jsfiddle.net/KRmJG/
Got this one to work straight away after hassle with the jQuery LocalScroll
This seems clean and easy!
I see other people asked as well before.
I am also trying to find a solution for a horizontal site I am working on.
Could this be modified to work in that case?
Any hints would be extremely helpful…
Ok… thankfully that didn’t take too much to figure out.
Using the second method I used this code and it worked:
$(function(){
$('a[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) {
var targetOffset = $target.offset().left;
$('html,body').animate({scrollLeft: targetOffset}, 1000);
return false;
}
}
});
});
I’ve been testing a bunch of different code for smooth scrolling over the last couple of days and these seem to be the most straight forward and easy to implement. I’m a designer not a coder so the simpler the better. Awesome stuff.
Just one issue. I noticed Fumie asked about having the hash link appear in the URL and Michal Kopanski pointed out that technique #1 let’s you keep the hash links, while technique #2 does not.
The problem I’m having with #1 is that I can’t link to the hash links from a different page (e.g. from the home page there’s a link something like “about#sometag”). Is there a way to have the hash links appear using technique #2?
I have external anchor links on my page that doesn’t work anymore when using the script :-(
Chris Coyer for President!
If you want to prevent that the animations “queue up” replace this line:
$('html,body').animate({with this:
$('html,body').stop().animate({Yay!!!
Thank you sooooo much, my website is 10x better looking now and your code was so easy to use!
xo
This is great but it dont want the top to be the top of the browser….
I have a fixed header at the top and i want the point it scrolls to, to be the bottom of the header.
Regardless what i do it will always scroll the anchor to the very top of the browser :(
Anyway of achieving this?
Hi all,
just thought I’d point out that script 1 may cause you problems if you are linking to # anchors on other pages than the one you are on.
If the link were on the same page then the jQuery works fine.
If any one knows of a solution for enabling # links to other pages, that would be great !
Thanks
Thank you for the script. I just have one question: Why would you not use the anchor text in the URL? Has it any benefits? In my eyes it just makes the user experience less. It feels like working in flash. :)
We use a content management system that sometimes requires anchors within links to other pages. I’d love to be able to switch the choice off but I’m afraid we’re stuck with it !
Alas, the above two scripts won’t work for links such as this:
http://www.mysite.com/otherpage.html#someanchor
The first method seemed a bit laborious with the separated function, so I integrated it into the bind command as a callback function. Seems to work perfectly fine, though I’ve only tested it in Chrome and IE7.
$(document).ready(function() {
$('a[href*=#]').bind('click', function(e) {
e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump
var target = $(this).attr("href"); //Get the target
// perform animated scrolling by getting top-position of target-element and set it as scroll target
$('html, body').stop().animate({ scrollTop: $(target).offset().top }, 2000, function() {
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
return false;
});
});