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?
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With