Search code examples
javascriptjqueryevent-handlinglive

.on does not work in place of live


I have known for a while now that .on is supposed to replace .live, however I have never been able to get it to work at all.

I have tried:

$(this).on('click', function(){
    // Do something...
})

$(this).on({
    click: function(){ // Do something }
})

But it never works for me!

Specifically when I'm trying to bind events to elements that may not exist on the page initially.

Could someone please clear this up for me once and for all?


I'm using the latest version of jquery.


Solution

  • For dynamically generated elements you need to use like

    $(document).on('click','YOUR SELECTOR', function(){
    
    });
    

    It's because document is the container of your elements which can watch changes to the DOM. For every action, there needs to be an explicit event listener. If you bind something to $(this), it (the selector) might not exist when you remove it.