Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preventing onclick page jumps

Tags:

javascript

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?

like image 372
ian Avatar asked Oct 27 '09 16:10

ian


3 Answers

I always use

<a href="javascript:void(0)" onclick="blahblah">
like image 178
Gordon Tucker Avatar answered Nov 16 '22 14:11

Gordon Tucker


Returning false in 'onclick' prevents page jump

<a href="#" onclick="someFunction(); return false;">blah</a>
like image 4
Vertigo Avatar answered Nov 16 '22 15:11

Vertigo


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>
like image 3
Xavi Avatar answered Nov 16 '22 16:11

Xavi