gabor_Csapo gabor_Csapo - 6 months ago 30
Javascript Question

How can I scroll the page to an element after being re-directed from another page?

<script>
$(document).ready(function () {
$("#button").click(function () {
window.location.href = "page2.aspx";

$('html, body').animate({
scrollToElement ("#div").offset().top
}, 2000);
});
});
</script>


The idea, is that you click a button on page1, then you get redirected to page2 and then you scroll to a specific element using jQuery.

Answer

You can always set an anchor for that element, like so

<a name="scroll"></a>
<h2>I wanna scroll here</h2>

And link to it: http://mydomain.com/index.php#scroll

The only benefit in using jQuery for this task would be to animate the scrolling itself, in which case you do something like this:

<h2 id="scrollhere">I wanna scroll here</h2>

Link here: http://mydomain.com/index.php#scrollhere

And then in jQuery in the redirected page:

$(document).ready(function() {
    if (window.location.hash != null && window.location.hash != '') 
        $('body').animate({
            scrollTop: $(window.location.hash).offset().top
        }, 1500);
});
Comments