Reputation: 2337
When I want a function to stop a link and continue on executing my own code, I do this:
// IE
if (e.cancelBubble) {
e.cancelBubble = true;
}
// Firefox
if (e.stopPropagation) {
e.stopPropagation();
}
// Others
if (e.defaultPrevented) {
e.defaultPrevented();
}
alert('still executing my function');
Is all that really necessary, or could I do it with less code?
Upvotes: 1
Views: 544
Reputation: 22395
Simply make the function return false
for javascript.
Since you mentioned in your comment you are using a jQuery click method, add the event.preventDefault()
.
$('#mylink').click(function(event) {
event.preventDefault();
//code here
})
jquery Source (thanks to BenjaminGreunbaum) for pointing out that jQuery normalizes events, thus event.returnValue
is already handled.
For javascript, you'll want to add an eventListener
.
function derp(event) {
event.preventDefault();
}
document.getElementById("mylink").addEventListener('click', derp, false);
Upvotes: 4
Reputation: 3962
Write a simple return false;
statement.
This will work in all browsers.
Upvotes: 1
Reputation: 8251
You can use return false
as it is effectively the same as calling both e.preventDefault
and e.stopPropagation
e.preventDefault()
will prevent the default event from occurring, e.stopPropagation()
will prevent the event from bubbling up and return false
will do both.
Upvotes: 1