Search code examples
javascriptjquerycssscrollpage-jump

Javascript anchor target scrollTo top don't work


Information

I use target to change some CSS. That means I need to behaviour of target to continue to work. preventDefault might not be an option?

Problem

I expected the window.scrollTo(0, 0); would work to make the page jump to the top. That did not happend. Why not? Solution?

jsfiddle

You can try it out on jsfiddle. Scroll down to see the demo. I added padding.

HTML

<a href="#test">Test</a>
<div id="test">My content</div>

Javascript (jQuery)

$("a").on("click", function(e){
    window.scrollTo(0, 0);
});

CSS

div {
    background: green;
}
#test:target {
    background: red;
}

a {
    padding-top: 1900px;
    display: block;
}

Solution

  • I answer this one myself. I found out a solution that worked in all cases I tried. None of the other answers did.

    http://jsfiddle.net/8dmtN/6/

    To prevent strange jumping

    • Avoid animate scrollTop

    Keep anchor state

    • Redirect it with window.location.
    • Then scroll to top.

    jQuery

    jQuery(document).ready(function($) {
        $("a").on("click", function(e){
            e.preventDefault();
            var hash = $(this).attr('href');
            window.location = hash;
            window.scrollTo(0, 0);
        });
    });