Search code examples
jqueryevent-delegation

Jquery - Bind delegate to all "a" tags


i try to block the jq click() when you click on an link in a div.

HTML

<div id="all">
    <div id="test">
        <a href="http://google.de">google</a>
    </div>
</div>

JS

$('#test').click(function() { alert('only when i click the div');  });

$('a').click(function(e) {
    e.stopPropagation();
    e.preventDefault();
    $('body').append(e.target.href);
});       

This code works great but my content is dynamically so i need a delegate() solution.

The code below dont work. But why? Whats the problem?

$('#all').delegate("a", "click", function(e)
{
    e.stopPropagation();
    e.preventDefault();
    $('body').append(e.target.href);
});

example
http://jsfiddle.net/Lf3hL/13/


Solution

  • stopPropagation doesn't work with delegate - http://api.jquery.com/event.stopPropagation/

    Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will propagate to the elements to which they are delegated; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false.

    Now if you change your test click to use a delegate and use stopImmediatePropagation it will work

    $('#all').delegate('#test', 'click' ,function() {
        alert('only when i click on the div');
    });    
    
    $('#all').delegate("a", "click", function(e)
    {
        e.stopImmediatePropagation();
        e.preventDefault();
        $('body').append(e.target.href);
    }); 
    

    http://jsfiddle.net/Lf3hL/14/