HTML anchor link - href and onclick both?

psychotik picture psychotik · Aug 28, 2009 · Viewed 272.6k times · Source

I want to author an anchor tag that executes some JavaScript and then proceeds to go wherever the href was taking it. Invoking a function that executes my JavaScript and then sets window.location or top.location to the href location doesn't work for me.

So, imagine I have an element with id "Foo" on the page. I want to author an anchor similar to:

<a href="#Foo" onclick="runMyFunction(); return false;">Do it!</a>

When this is clicked, I want to execute runMyFunction and then jump the page to #Foo (not cause a reload - using top.location would cause it to reload the page).

Suggestions? I am happy to use jQuery if it can help here...

Answer

Amber picture Amber · Aug 28, 2009

Just return true instead?

The return value from the onClick code is what determines whether the link's inherent clicked action is processed or not - returning false means that it isn't processed, but if you return true then the browser will proceed to process it after your function returns and go to the proper anchor.