• Stop distribution using jquery delegate / live function not working

    Here is the html problem:

    <ul id="update-list"> <li class="update" onclick="window.location('some_url')"> <h2> some header </h2> <p> some paragraph </p> <div> <a class="popup-link"> <span> Show Popup </span> <span> + </span> </a> </div> </li> // this repeats n times //... </ul> 

    When I click on the .popup-link , it should only open a pop-up window (it does), but it also starts inline onclick on li . The fact is that li tags are part of a partial that is retrieved through ajax on different pages. Therefore, I use jquery delegate to bind events as follows:

     $('#update-list').delegate('.popup-link', 'click', function(e){ // e.target is <span> while e.currentTarget is .popup-link e.stopPropagation(); //console.log(e.isPropagationStopped()); this shows 'true' in console $.popup(); // launch popup e.preventDefault(); // or return false }); 

    This does not seem to work, and the built-in onclick fires anyway. I tried with live() but did not achieve anything. Is something missing here?

    +4
    source share
    4 answers

    AFAIK, you cannot reliably prevent a built-in event handler from starting by stopping bubbles inside an attached event handler.

    Also, using live() or .delegate() , you cannot use preventDefault() and stopPropagation() . You need to return false to prevent the phase of the bubbles and the default behavior.

    In any case, as I mentioned, you cannot prevent the inline event handler from starting.

    So, create it completely unobtrusive (this is what I highly recommend), or remove the inline click handler in the code.

    Example:

     $('#update-list').delegate('.popup-link', 'click', function(e){ $.popup(); // launch popup return false; }).delegate('.update', 'click', function(){ window.location('some_url'); }) // the rest of this is unnecessary if you can just omit the onclick attribute .find('.update') .removeAttr('onclick'); 

    Ref . : . delegate ()

    +4
    source

    Can you try this?

     $('#update-list').delegate('.popup-link', 'click', function(e){ // e.target is <span> while e.currentTarget is .popup-link e.stopPropagation(); e.preventDefault(); // or return false // open popup in a timeout so that this function can return false window.setTimeout(function() {$.popup();}, 20); // for IE e.cancelBubble = true; return false; }); 
    0
    source

    You can try this because .delegate() been replaced by the .on() method.

    It works great

    0
    source
      $('#update-list').delegate('.popup-link', 'click', function(e){ e.stopImmediatePropagation(); e.preventDefault(); // do something... }); 
    0
    source

    All Articles