Reputation: 5301
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.
Upvotes: 19
Views: 14959
Reputation: 20415
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.
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.
Upvotes: 22
Reputation: 3414
It can be done like this:
<a onclick="JavaScriptCodeHere; return true;" href='bla..'>link</a>
1) The onclick needs to be before the href.
2) return true; makes sure that user will be taken to the linked page after your JS code executes. If you use return false;
- linked itself will not work, it will just fire your JavaScript on click;
Upvotes: 1
Reputation: 4497
after performing your desired action why don't you just redirect it to the page by adding this line:
window.location = 'welcome.php';
Upvotes: 4
Reputation: 38533
The link will not go till after the work is done, so you can do:
$('a').click(function(ev){
//do something here
});
Upvotes: 5
Reputation: 43094
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.
Upvotes: 5