I bind to a link (by using the .live()
function of jQuery) click
event and then manually add an onclick
event handler with pure JS and HTML (like <a href="".... onclick="some action">
). I want to prevent bubbling of the event to the live
method but I don't know how.
Maybe e.stopPropagation()
is helpful in this situation but the event handler added with onclick
is written in pure JS and I can't call stopPropagation()
from outside the jQuery element wrapper. return false
in this situation does not work. I tried to substitute return false
with $.Event('click').stopPropagation()
but I think this is wrong as it did not work.
How to prevent bubling to live()
method without jQuery wrapper?
The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.
stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.
The event. preventDefault() will not allow the user to leave the page and open the URL. The event. stopPropagation() method stops the propagation of an event from occurring in the bubbling or capturing phase.
Stop propagation is needed when you have JavaScript running on the same event of nested elements. Imagine having a click event on a parent element AND a child. If you clicked the child, and don't want it to also count as a click for the parent, then you need to stop propagation in the child click handler.
I was under the assumption that return false
in "normal" event handlers prevents the event from bubbling as well, but I was wrong (thanks @Mrchief).
There are other ways to stop it though, as described on quirksmode.org:
function doSomething(e)
{
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
cancelBubble
is for IE, stopPropagation
works in all W3C compatible browsers.
With .live, you cannot stop propagation. This is because with .live
, the event handler is bound to the root of the DOM tree. Hence the event must bubble upto the highest element before your handler can be called. Its one of the caveats on using .live
.
Consider using .delegate (if you want the handler to persist) or use .bind instead.
If you want the live handler to be disabled completly, use die:
$("#myHref").die("click", aClick); // this will remove any existing event handlers
$("#myHref").click(yourhandler); // add your handler
Demo 1: JsFiddle 1
Or, add an inline handler (and cancel the event from there):
<a href=".." onclick="yourhandler">
Demo 2: JsFiddle 2
Inline handlers will be called first always before any jquery event handlers.
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