1

I'm pretty sure that the answer isn't that difficult, but I'm not sure where to look for it.

I would like to attach a jQuery event handler when a div gets created. For example:

$('#somediv').click(function(){
    //do something
});

But... #somediv doesn't exist. Because of some AJAX loads it will. So what I need is something like.

$('#somediv').whenImcreated(function(){
    $(this).click(function(){
        //do something
    });
});
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
Bob van Luijt
  • 6,076
  • 9
  • 46
  • 85

2 Answers2

3

You need a delegated event:

$(document).on('click', '#somediv', function(){
    //do something
});

Note that while document as the primary selector will work, for best performance you should make it the closest parent element of #somediv which is present in the DOM on document.ready.

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
  • A good start, but OP asked when it was *created*, not when it was clicked. Do you have an event for when the div 'comes to life'?? – Berto Oct 13 '17 at 19:04
  • I suggest you read and understand the question. While the OP says they want to know when the element is created it's obvious they are trying to attach an event handler after it has been added to the DOM. If you really want to have an event fired when an element is created, use a MutationObserver, something like this: https://stackoverflow.com/a/19401707/519413 – Rory McCrossan Oct 14 '17 at 16:14
2

Use .on()

As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.

$(document).on('click', '#somediv', function(){ ... });

Syntax

$( elements ).on( events, selector, data, handler );
Tushar Gupta - curioustushar
  • 54,013
  • 22
  • 95
  • 103