Search code examples
jqueryjquery-on

Jquery On and Live Confusion


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?


Solution

  • .on does work with dynamic content, but you have to use a different version of it, like so...

    $("static-scope-selector").on("event", "dynamic-content-selector", function{...});
    

    So, with your markup, you would use something like this:

    $("div.ex").on("hover", ".text", function(e) {...})
            .on("click", ".text", function(e) {...});