link with href="#" scrolls page to top when used with jquery slidetoggle [duplicate]
Asked Answered
A

4

28

Possible Duplicate:
How do I stop a web page from scrolling to the top when a link is clicked that triggers javascript?

I'm using jquery's slidetoggle to show/hide divs. the element that controls the sliding is a text link ( some text inside <\a>) which has href="#" so it will look like a link (underline, cursor change).

the problem is that when the link is clicked, in addition to the sliding effect, the page scrolls to top.

i tried replacing href="#" with href="" but that disables the div show/hide effect. i guess i could add to the tag Name="somename" and then set the href to href="#somename" but i would rather not use tricks like that.

why is href="#" scrolling the page to its top?

any ideas would be highly appreciated

Ambulator answered 7/1, 2010 at 23:1 Comment(1)
You could just use href="#id-of-choice" to move the page to an element with id="id-of-choice"Rhonarhonchus
G
76

Several options:

  1. Put return false; at the bottom of your click handler and the href wont be followed.
  2. Change the href to javascript:void(0);
  3. Call preventDefault on the event in your handler:

    function( e ) {
      e.preventDefault();
      // your event handling code
    }
    
Gaddi answered 7/1, 2010 at 23:2 Comment(3)
thank you all for your answers. i used return false and it works perfectly stackoverflow is amazing !Ambulator
Excellent solution thenduks, saved me a lot of hassle=)Lariat
return false; is NOT the correct way to handle this. So often, developers lazily throw return false; at the end of their event handlers without understanding the consequences of this action. There is no reason to prevent propagation of the event. All you need to do here is prevent the user agent's default action. So, preventDefault() is the correct function to use here.Directly
A
5

You need to add return false; to your click handler.
This will prevent the browser from executing the default action for the click.

Accad answered 7/1, 2010 at 23:2 Comment(0)
B
1

Others have given you solutions. But to specifically answer your question, # refers to the current page. And since the interpretation of tags is to bring the top of the tag into view, clicking on a # tag scrolls you to the top of the current page.

Blackguardly answered 7/1, 2010 at 23:8 Comment(0)
L
1

return false or event.preventDefault() are what you need in your click event handler to prevent the default action from occurring. An <a> element with a href of # will cause the browser viewport to jump to the top of the page as the default action

Linnette answered 7/1, 2010 at 23:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.