Code :
$('#myLink').click(function (e) {
e.preventDefault();
...
if (someCondition) {
... code ...
} else {
... execute the link
}
});
I'd like, if someCondition
is false, execute the original href of the link (so, go that link, changing the page). Is it this possible?
The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
As you probably might have already worked out based on the simple explanation above: the opposite of event. preventDefault() is nothing. You just don't prevent the event, by default the browser will allow the event if you are not preventing it.
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 main difference between return false and event. preventDefault() is that your code below return false will not be executed and in event. preventDefault() case your code will execute after this statement.
$('#myLink').click(function (e) {
e.preventDefault();
...
if (someCondition) {
//do stuff
} else {
location.href = $(this).attr('href');
}
});
Just move the preventDefault
inside the if/else statement:
$('#myLink').click(function (e) {
...
if (someCondition) {
e.preventDefault();
... code ...
} else {
... execute the link
}
});
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