tags:

views:

74

answers:

3

Hi,

Is there a way to push the browser back to the top of the page when a link is clicked? I am dynamically changing some content but the project needs the user to start at the top of the page when the new content is loaded.

I am already using the url hash tag to keep track of the history. Just looking for some type of javascript function to do this.

+5  A: 

What you probably want is scroll(0,0).

As a link:

<a href="javascript:scroll(0,0)">back to the top</a>

Or just the javascript itself (integrated in a function):

function onContentLoad() { 
  scroll(0,0);
}

For further reference: http://developer.mozilla.org/en/window.scroll http://msdn.microsoft.com/en-us/library/

inflagranti
+1 A good answer that could be made great with a link to documentation and more context (e.g., that `javascript:` prefix means you're putting that in a link; I don't actually think he wants it in a link, but either way, either show the link or just show the JavaScript on its own).
T.J. Crowder
@JasonS: References: https://developer.mozilla.org/en/window.scroll http://msdn.microsoft.com/en-us/library/ms536726(v=VS.85).aspx Works in IE, Firefox, and WebKit-based browsers (Safari, Chrome) at least, probably more.
T.J. Crowder
He wrote 'when a link is clicked', hence I assumed he wants a link. I extended the code a bit.
inflagranti
@inflagranti: *"He wrote 'when a link is clicked'..."* Why, sure enough, he did. Sorry, I missed it, and the rest of his question seemed like he would want to do it in code. In any case, nice edits. :-) (Though again, references are useful; heck, I'd even looked them up for you.)
T.J. Crowder
Hehe, yeah, thats why I thought there is no need to add the reference to my answer as its in the comments... Did it now though :)
inflagranti
A: 

You could create an anchor at the top of the page wether it contain text or not. Then on your link have to refer to the anchor.

Example:

Create an anchor:

<a name="tips">Useful Tips Section</a>

or

<a name="top"></a>

Then create a link to said anchor:

<a href="#tips">Visit the Useful Tips Section</a> 

or

<a href="#top">Go to top.</a>

Ta da.

Thqr
Except that he's "already using the url hash tag to keep track of the history"
gregers
@gregers fair enough completely disreguarded that >.> (I'll still leave it here though always nice to have multiple answers if someone else comes a looking one day)
Thqr
+3  A: 

inflagranti's answer is right about the way to do it using javascript.

If you use jQuery you can also animate the scroll to top action.

$('html, body').animate({scrollTop:0}, 'slow');
ppolyzos