1

Im using a plugin (Event Organiser Pro) that dynamically creates a div based on the input of a number field - basically it creates a duplicates the form fields depending on the number you enter in the input field.

I need to run some jQuery which is based on those form fields, but obviously cant run it until the div has been created.

How can i run the script once the div has been created? Is it possible to run script when div id has been created? Or something similar?

Futwill
  • 23
  • 2

1 Answers1

1

Yes, you can delegate the DOMNodeInserted event to the body.

function createDiv() {
 $('<div />').addClass('test').appendTo($('body'));
}

$('body').on('DOMNodeInserted', '.test',function() {
 alert('Created element .test');
})

$("button").on('click', function() {
 createDiv();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create</button>

In the example above the click on the button simulates your other script creating the div.

To rewrite the code to work with your setup you can strip the click part out and delegate the event listener to your id:

$('body').on('DOMNodeInserted', '#your_element',function() {
 yourFunction();
    // call a function here or add your code here directly
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Note: This example won't work here because the element with that ID does not exist and neither does the yourFunction() function.

Jonas Grumann
  • 10,438
  • 2
  • 22
  • 40
  • Thanks for this, very helpful. So as the div appears once a number is entered into the input field and then click off, would i do this by doing the below? Obviously i don't a button, so i was hoping for it to be able to detect when a specific div id appears. `function createDiv() { jQuery('
    ').addClass('test').appendTo(jQuery('body')); } jQuery('body').on('DOMNodeInserted', '.test',function() { // Run my script here }) jQuery("#eo-booking-field-dob-eoc1").change(function() { createDiv(); })`
    – Futwill Mar 06 '17 at 13:08
  • I updated the answer with only the code that you need for your case, you have to change the id and insert the correct function anme – Jonas Grumann Mar 06 '17 at 13:17