Attaching click event to a JQuery object not yet added to the DOM [duplicate] Attaching click event to a JQuery object not yet added to the DOM [duplicate] javascript javascript

Attaching click event to a JQuery object not yet added to the DOM [duplicate]


Use this. You can replace body with any parent element that exists on dom ready

$('body').on('click', '#my-button', function () {     console.log("yeahhhh!!! but this doesn't work for me :(");});

Look here http://api.jquery.com/on/ for more info on how to use on() as it replaces live() as of 1.7+.

Below lists which version you should be using

$(selector).live(events, data, handler); // jQuery 1.3+

$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+

$(document).on(events, selector, data, handler); // jQuery 1.7+


I am really surprised that no one has posted this yet

$(document).on('click','#my-butt', function(){   console.log('document is always there');}) 

If you are unsure about what elements are going to be on that page at that time just attach it to document.

Note: this is sub-optimal from performance perspective - to get maximum speed one should try to attach to the nearest parent of element that is going to be inserted.


Try this.... Replace body with parent selector

$('body').on('click', '#my-button', function () {    console.log("yeahhhh!!! but this doesn't work for me :(");});