Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 689
Keith L. Avatar asked Dec 22 '22 03:12

Keith L.


1 Answers

As of 1.7 .live() has been deprecated and .delegate() has been superseded by .on()

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

.on() is the super binder now ;)

Try to bind to the closest thing to your target which will definitely contain it, preferably something with an ID:

<div id="mainContent">
    <div class="myDiv"></div><!-- Dynamically created div -->
</div>

a great target here would be #mainContent

$("#mainContent").on("click","div.myDiv",function () { 
    var Pos = $(this).offset(); 
    $("#Container").css("left", Pos.left).css("top", Pos.top); 
});
like image 86
Sinetheta Avatar answered Jan 02 '23 18:01

Sinetheta