Is there any way to prevent default event and then fire it again with jQuery?

Dimskiy picture Dimskiy · May 19, 2011 · Viewed 14.1k times · Source

Basically I have an anchor element, <a href='bla..'>link</a>

On click, I first want to do something and only once it's done I want to take the user to the page that it links to. Something like:

$('a').click(function(ev){
   ev.preventDefault();

   //do something here

   ev.refireDefault();
});

Any suggestions?

Update

My apologies! My FireFox decided to cache the previous version of JS, so nothing that I tried worked until a simple CTRL+F5 solved the issue.

Answer

Code Maverick picture Code Maverick · May 19, 2011

Javascript is not multi-threaded. It is event driven and events fire in the order in which you load them. Therefore, if you simply leave out the ev.preventDefault() in your click event altogether, it won't fire the default action until the function exits.

See jsFiddle here


EDIT per @Greg's comment:

The only scenario in which the above is not true is with asynchronous functions. In that scenario you would want to prevent the default action first and then in the asynchronous callback function, re-fire the default action.