jQuery scroll to ID from different page
Combining answers by Petr and Sarfraz, I arrive at the following.
On page1.html:
<a href="page2.html#elementID">Jump</a>
On page2.html:
<script type="text/javascript">
$(document).ready(function() {
$('html, body').hide();
if (window.location.hash) {
setTimeout(function() {
$('html, body').scrollTop(0).show();
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 1000)
}, 0);
}
else {
$('html, body').show();
}
});
</script>
On the link put a hash:
<a href="otherpage.html#elementID">Jump</a>
And on other page, you can do:
$('html,body').animate({
scrollTop: $(window.location.hash).offset().top
});
On other page, you should have element with id set to elementID
to scroll to. Of course you can change the name of it.
You basically need to do this:
- include the target hash into the link pointing to the other page (
href="other_page.html#section"
) - in your
ready
handler clear the hard jump scroll normally dictated by the hash and as soon as possible scroll the page back to the top and calljump()
- you'll need to do this asynchronously - in
jump()
if no event is given, makelocation.hash
the target - also this technique might not catch the jump in time, so you'll better hide the
html,body
right away and show it back once you scrolled it back to zero
This is your code with the above added:
var jump=function(e)
{
if (e){
e.preventDefault();
var target = $(this).attr("href");
}else{
var target = location.hash;
}
$('html,body').animate(
{
scrollTop: $(target).offset().top
},2000,function()
{
location.hash = target;
});
}
$('html, body').hide();
$(document).ready(function()
{
$('a[href^=#]').bind("click", jump);
if (location.hash){
setTimeout(function(){
$('html, body').scrollTop(0).show();
jump();
}, 0);
}else{
$('html, body').show();
}
});
Verified working in Chrome/Safari, Firefox and Opera. I don't know about IE though.
I would like to recommend using the scrollTo plugin
http://demos.flesler.com/jquery/scrollTo/
You can the set scrollto by jquery css selector.
$('html,body').scrollTo( $(target), 800 );
I have had great luck with the accuracy of this plugin and its methods, where other methods of achieving the same effect like using .offset()
or .position()
have failed to be cross browser for me in the past. Not saying you can't use such methods, I'm sure there is a way to do it cross browser, I've just found scrollTo to be more reliable.