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?
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.
The preventDefault() Method in jQuery is used to stop the default action of selected element to occur.
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.
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.
The preventDefault() method of an event is used to stop a cancelable event from executing.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With