jQuery cross-browser "scroll to top", with animation
You're returning true
from the click function, so it won't prevent the default browser behaviour (i.e. navigating to thego-to-top
anchor. As Mark has said, use:
$('html,body').animate({ scrollTop: 0 }, 'slow');
So your code should now look like:
$('#go-to-top').each(function(){ $(this).click(function(){ $('html,body').animate({ scrollTop: 0 }, 'slow'); return false; });});
To get it to work in opera this answer proved helpful.
Putting that with your click()
$(this).click(function() { $(window.opera ? 'html' : 'html, body').animate({ scrollTop: 0 }, 'slow');});
Side note if all you are doing with the .each()
is assigning a click handler you do not need to iterate over the collection it can be simplified to this:
$('#go-to-top').click(function(){ $(window.opera ? 'html' : 'html, body').animate({ scrollTop: 0 }, 'slow');});
Also if there is more than one element with id #go-to-top
your markup will be invalid, try switching it to a class .go-to-top
maybe something like
$('body').animate({scrollTop:0}, 'slow');
aswell as the html one.
edit >
$('#go-to-top').each(function(){ $(this).click(function(){ $('html').animate({ scrollTop: 0 }, 'slow'); return true; $('body').animate({ scrollTop: 0 }, 'slow'); return true; $('document').animate({ scrollTop: 0 }, 'slow'); return true; $('window').animate({ scrollTop: 0 }, 'slow'); return true; });});
should cover all browsers!