0

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?

mausmust
  • 105
  • 1
  • 1
  • 7

1 Answers1

0

.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) {...});
Todd Gibson
  • 1,005
  • 7
  • 16