views:

1852

answers:

3

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 JS 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...

+10  A: 

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.

Amber
I'm afraid that browser won't wait for runMyFunction() to execute.
n1313
@n1313 - It will. It has to, otherwise it doesn't know what onClick's return value is and thus doesn't know whether or not to actually process the href.
Amber
@Dav - Just tested it and yes, you are right.
n1313
Or just remove the return statement entirely.
DisgruntledGoat
+1  A: 

If the link should only change the location if the function run is successful, then do onclick="return runMyFunction();" and in the function you would return true or false.

If you just want to run the function, and then let the anchor tag do its job, simply remove the return false statement.

As a side note, you should probably use an event handler instead, as inline JS isn't a very optimal way of doing things.

peirix
+2  A: 
<a href="#Foo" onclick="return runMyFunction();">Do it!</a>

and

function runMyFunction() {
  //code
  return true;
}

This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

n1313