Search code examples
jquerydelegatecommand

jQuery: live() and delegate()


I'm binding a click event to a div element, which is created after clicking on a button. I'm using .live() and this is working. I've heard, that I should not use .live, but .delegate(). So I've tried it, but it is not working, but .live is working.

My working jQuery:

$(".myDiv").live("click",function () {
    var Pos = $(this).offset();
    $("#Container").css("left", Pos.left).css("top", Pos.top);
});

The not working jQuery:

$(".myDiv").delegate("div","click",function () {
    var Pos = $(this).offset();
    $("#Container").css("left", Pos.left).css("top", Pos.top);
});

My HTML for the div

<div class="myDiv"></div>

Can anyone tell me, why delegate is not working for me?


Solution

  • Your mistake is that you are not correctly specifying which elements should trigger the event handler (using the selector in the first parameter of delegate) and which parent element is responsible for firing off the event (using the selector in the jQuery object which starts the chaining).

    The correct way is something like

    $("body").delegate("div.myDiv","click",function () { 
        var Pos = $(this).offset(); 
        $("#Container").css("left", Pos.left).css("top", Pos.top); 
    }); 
    

    See the examples for delegate.

    For jQuery 1.7 and upwards, delegate (along with all other event binding methods) has been superseded by the on method, which would be used in the exact same manner:

    $('body').on('click','div.myDiv',function() {
        // ...
    });