-2

I have a page that when a certain event happens, I want the screen to automatically scroll back to the top.

I want the script to wait 2 seconds, and then it takes 2 seconds to scroll to the top of the page.

        // Scroll to top
        setTimeout(function(){
            alert('scroll');
            $('html, body').animate({scrollTop : 0}, 2000);
        }, 2000);

I get the alert after 2 seconds, but the screen doesn't move.

Is there something wrong with my scrollTop code?

b85411
  • 9,420
  • 15
  • 65
  • 119
  • Are you sure the scrollbar is attached to the outer most element, and not a nested element etc. – adeneo Apr 09 '15 at 08:16
  • http://stackoverflow.com/questions/16475198/jquery-scrolltop-animation ? – Alexey Apr 09 '15 at 08:17
  • Did you close the alert popup? that stops the code execution – slash197 Apr 09 '15 at 08:17
  • I tried `alert($("body").scrollTop());` and it came back as `0` if that helps - even though I'm at the bottom of the page? – b85411 Apr 09 '15 at 08:21
  • Actually - the scrolling part I don't really care so much about. All I require is that the focus is at the top of the page again, whether it scrolls there or it just appears there I don't mind. Maybe there's a way I can just make it appear there, like if you click an anchor in HTML? Something like that? – b85411 Apr 09 '15 at 08:30

2 Answers2

0

I have another solution to you

use window.scrollTo(x-coord, y-coord);

x-coord is the pixel along the horizontal axis.
y-coord is the pixel along the vertical axis.
  • Unfortunately that didn't work. I'm not sure if it's relevant - but I am using twitter-bootstrap and looking at this in Chrome mode as an iPhone (ultimately I want this functionality to work on a mobile phone). – b85411 Apr 09 '15 at 08:22
0

try this once.

$(window).load(function() {
    setTimeout(function(){ 
    $(document).scrollTop($(target).offset().top);
    }, 1000);
});
Vishal
  • 537
  • 3
  • 13