Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 372
Dimskiy Avatar asked May 19 '11 15:05

Dimskiy


People also ask

Which method is used to stop default triggering action in jQuery?

The preventDefault() Method in jQuery is used to stop the default action of selected element to occur.

How would you stop the default action of an event?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

What can I use instead of event preventDefault?

The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault() . Nowadays, you should usually use native HTML form validation instead.

Which method cancels event default behavior in Javascript?

The preventDefault() method of an event is used to stop a cancelable event from executing.


2 Answers

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.

like image 139
Code Maverick Avatar answered Oct 21 '22 15:10

Code Maverick


preventDefault marks the event as handled so that when your click function exits, the default action isn't taken. If you don't call preventDefault then the default click action won't get called until your click function exits. So remove it and it'll work as you are suggesting.

like image 20
Lazarus Avatar answered Oct 21 '22 15:10

Lazarus