Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  197] [ 2]  / answers: 1 / hits: 39883  / 12 Years ago, thu, may 3, 2012, 12:00:00

When I use event.preventDefault() on a link it works, however when I use it on a button doesn't!



DEMO



My code:



<a id=link href=http://www.google.com>link</a>
<button id=button onclick=alert('an alert')>button</button>​

$('#link').click(function(event){
event.preventDefault();
});
$('#button').click(function(event){
event.preventDefault();
});



Link action is cancelled, but when I click on the button, still executes the onClick action.



Any help? what I want to do is to prevent the button onClick action without changing the button html (I know how to do



$('#button').removeAttr('onclick');


More From » jquery

 Answers
16

You want event.stopImmediatePropagation(); if there are multiple event handlers on an element and you want to prevent the others to execute. preventDefault() just blocks the default action (such as submitting a form or navigating to another URL) while stopImmediatePropagation() prevents the event from bubbling up the DOM tree and prevents any other event handlers on the same element from being executed.



Here are some useful links explaining the various methods:





However, since it still doesn't work it means that the onclick= handler executes before the attached event handler. There's nothing you can do since when your code runs the onclick code has already been executed.



The easiest solution is completely removing that handler:



$('#button').removeAttr('onclick');


Even adding an event listener via plain javascript (addEventListener()) with useCapture=true doesn't help - apparently inline events trigger even before the event starts descending the DOM tree.



If you just do not want to remove the handler because you need it, simply convert it to a properly attached event:



var onclickFunc = new Function($('#button').attr('onclick'));
$('#button').click(function(event){
if(confirm('prevent onclick event?')) {
event.stopImmediatePropagation();
}
}).click(onclickFunc).removeAttr('onclick');

[#85821] Wednesday, May 2, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brandt

Total Points: 43
Total Questions: 90
Total Answers: 111

Location: Aruba
Member since Fri, Jun 24, 2022
2 Years ago
brandt questions
Sun, Jul 4, 21, 00:00, 3 Years ago
Wed, Jun 30, 21, 00:00, 3 Years ago
Sat, Jan 23, 21, 00:00, 3 Years ago
Mon, Sep 21, 20, 00:00, 4 Years ago
;