A few versions back jQuery got rid of the .live event handler. That handler was the way that you would handle events on elements being dynamically added to the page after the ready() event had fired. So with it gone you now use the .on handler, but it has one problem. It doesn’t work on elements that are dynamically added to the page. But you can make it work by using delegation, you attach it to an element that is there when ready fires, and use delegation filters to hit the one you are dynamically adding.

WRONG

PHP

1

2

3

4

5

jQuery(function($){

$("#mydynamicelement").on('change',function(){

alert("No one will ever see me :-(");

});

})

RIGHT

PHP

1

2

3

4

5

jQuery(function($){

$(document.body).on('change',"#mydynamicelement",function(){

alert("Look at me HOORAY :-)");

});

})

Note: Using document.body will give a slight hit on performance, much better to simply use a direct parent of the dynamic element, but make sure it is an element that is in the DOM when the page ready event fires.

Like the code you see here? You can hire me at Codeable.io - a WordPress specialist outsourcing site that vets developers to make sure they are of the highest standard. See all developers you can hire through Codeable here.