views:

74

answers:

3

I am running some JavaScript on my page. Whenever it catches an event that is attached to an anchor <a> element and executes the handler (which I've attached using jQuery) the scroll position resets back to the top of the page. Is there a solution?

A: 

I assume that you mean that whenever you postback to the server, the page is scrolled to the top.
If that's not what you mean, please clarify.

To solve this, you could use Javascript to send $(window).scrollTop() along with the postback, then write server-side code that emits more Javascript to scroll back down if it got the parameter.

If you want a more specific solution, please provide more details.

SLaks
+4  A: 

While handling clicks on <a> tags if you leave the href attribute as # the scroll thing you mention will happen. This is because the browser executes the default action at the end of the event chain (this happens because of the so called event bubbling)

To solve this you have to prevent the browser's default handling of the click event, this can be done in different ways:

  • replace href='#' with href='javascript:void(0)'
  • return false from your event handler function.
  • use jQuery's preventDefault method
Pablo Fernandez
As inline javascript is usually frowned upon no matter what, it is better to do `return false;` inside the binded function. This will work just fine, though.
Tatu Ulmanen
@pablo: you are a genius...:-) spot on.
amit
you could also do it by capturing the event and using preventDefault like so:$("a").click(function(event) { event.preventDefault();});
spelley
+5  A: 

One reason might be that you have links that are pointing at "#", and you have events bound to those links. The solution is to do return false; at the end of the event function:

<a href="#" id="foo">Test</a>

And in jQuery:

$('#foo').click(function() {
    /* do stuff */
    return false;
});
Tatu Ulmanen
thank you so much.
amit