views:

2896

answers:

5

I have a button a user presses and it shows a hidden div using jQuery.

My question is, how do I scroll to the top of the page using a jQuery command in that function? It is desirable if the scroll bar instantly jumps to the top. I'm not looking for a smooth scrolling.

+1  A: 

You could simply use a target from your link, such as #someid, where #someid is the div's id.

Or, you could use any number of scrolling plugins that make this more elegant.

http://plugins.jquery.com/project/ScrollTo is an example.

ScottE
+10  A: 

If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript window.scrollTo method -- passing in 0,0 will scroll the page to the top left instantly.

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

Parameters    
    * x-coord is the pixel along the horizontal axis.
    * y-coord is the pixel along the vertical axis.
MyWhirledView
+2  A: 

You don't need jQuery to do this. A standard HTML tag will suffice...

<div id="jump_to_me">
    blah blah blah
</div>

<a target="#jump_to_me">Click Here To Destroy The World!</a>
MatW
+6  A: 

If you do want smooth scrolling, try something like this:

$("a[href='#top']").click(function() {
  $("html").animate({ scrollTop: 0 }, "slow");
  return false;
});

That will take any <a> tag whose href="#top" and make it smooth scroll to the top.

Mark Ursino
+1. I was just wondering how to do something like this and google lead me here. QUestion though, where is "scrollTop" function in the docs? I just looked but couldn't find it.
lyrae
scrollTop is not function, it is a property of the window element
jalchr
+1  A: 

with window.scrollTo(0, 0); is very fast
so i tried the Mark Ursino example, but in Chrome nothing happens
and i found this

$('.showPeriodMsgPopup').click(function(){
    //window.scrollTo(0, 0);
    $('html').animate({scrollTop:0}, 'slow');//IE, FF
    $('body').animate({scrollTop:0}, 'slow');//chrome, don't know if safary works
    $('.popupPeriod').fadeIn(1000, function(){
        setTimeout(function(){$('.popupPeriod').fadeOut(2000);}, 3000);
    });
});

tested all 3 browsers and it works
i'm using blueprint css
this is when a client clicks "Book now" button and doesn't have the rental period selected, slowly moves to the top where the calendars are and opens a dialog div pointing to the 2 fields, after 3sec it fades

Luiggi ZAMOL