Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top