tags:

views:

647

answers:

4

what is the best way to stop my onclick links from causing the page to jump to the top.

<a name="point1">
<a href="#point1" onclick="blahblah">

<a href="javascript:" onclick="blahblah">

<a href="javascript:null;" onclick="blahblah">

Or something else?

A: 

Maybe this will do the trick?

<a href="javascript: return false;" onclick="blahblah">
Michal M
+1  A: 

Returning false in 'onclick' prevents page jump

<a href="#" onclick="someFunction(); return false;">blah</a>
Vertigo
Trying that now with this: onClick="submitComment('+[id]+'); this.onclick=null; return false; but it doesn't work.
ian
Strange. Returning false should prevent the default link action. Does it work if you try only onclick='return false;'?
Vertigo
Try changing onClick to onclick. Depending on the MIME type, onClick and onclick can be interpreted as two different attributes.
Xavi
if you're doing onClick="submitComment('+[id]+'); this.onclick=null; return false; then it's clear why return false is failing - you are setting the onclick attribute to null, I believe that will immediately stop the execution. I think. Have not tested it though.
artlung
+2  A: 

I always use

<a href="javascript:void(0)" onclick="blahblah">
Gordon Tucker
+1  A: 

Try this:

<a href="#" onclick="func(); return false;">link</a>

Notice that the onclick parameter returns false. Returning false cancels the default browser behavior. In the case of an anchor tag, the default browser behavior is to jump to the # anchor (aka the top of the page).

With this same trick you can also make image un-draggable and ensure that links don't steal the user's focus:

<img src="coolios.jpg" onmousedown="return false" /> <!-- un-draggable image -->
<a href="stuff.html" onmousedown="return false">link that doesn't steal focus</a>
Xavi