2

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;
}
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

3 Answers3

3

When you allready are using jQuery, I would do

$("a").on("click", function(e){
    $('html, body').animate({scrollTop:0}, 'fast');
});
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
1

You need to do use .preventDefault() method here to cancel the default action (navigation) of the click.

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

UPDATE

$("a").on("click", function (e) {
    e.preventDefault();
    $('#test').css('background-color', 'red')
    window.scrollTo(0, 0);
});

FIDDLE DEMO

palaѕн
  • 72,112
  • 17
  • 116
  • 136
1

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);
    });
});
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • 1
    gr8! I suggest you accept your own answer. By that people can see that the question actually _is_ answered and also learn from your experience. because it is "trusted" / accepted. – davidkonrad Sep 17 '13 at 21:29