Look at these example codes:
We have
<div class="ex"></div>
And we have jquery code;
1-With On
$('.ex').append("<div class='text'>object-1</div>");
$('.text').on({
hover: function(e) {
if (e.type === "mouseenter")
{
$(this).css('color','green');
}
else if (e.type === "mouseleave")
{
$(this).css('color','black');
}
},
click: function()
{
$(this).css('color','red');
}
});
$('.ex').append("<div class='text'>object-2</div>");
2-With Live
$('.ex').append("<div class='text'>object-1</div>");
$('.text').live({
hover: function(e) {
if (e.type === "mouseenter")
{
$(this).css('color','green');
}
else if (e.type === "mouseleave")
{
$(this).css('color','black');
}
},
click: function()
{
$(this).css('color','red');
}
});
$('.ex').append("<div class='text'>object-2</div>");
The problem is jquery is not working on object-2 with .on. .live is deprecated and should be avoided. However .on doesn't work with the dynamic content. How can i run jquery code on dynamic content with .on?