0

Say I want to hide a div with id="foobar", but foobar does not exist yet, only after user clicks a button and make an ajax call, the div gets populated into the DOM.

How do I write a function that runs once the div comes into existence? The function cannot be brought by the ajax call. It must exist before the call.

I learned that something like this might help:

$(document).ready(function () {
    $(document).on('click', '#futurebutton', function() {
        alert("You clicked the future button");
    });

but this seems to work only new button is clicked, what I need is having the function run once the div comes into existence.

so something similar to $(document).on( "COMES INTO EXISTENCE" , '#newdiv', function() ...

Thanks!

display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
eastboundr
  • 1,857
  • 8
  • 28
  • 46
  • There is no event for that. – epascarello Feb 07 '14 at 02:11
  • possible duplicate of [How can I determine if a dynamically-created DOM element has been added to the DOM?](http://stackoverflow.com/questions/220188/how-can-i-determine-if-a-dynamically-created-dom-element-has-been-added-to-the-d) – epascarello Feb 07 '14 at 02:12
  • 2
    Why can't you do it in the ajax success callback? Presumably you are creating the div at some point so you know when you need to hide it right? I supposed you can try this if you don't need to support old browsers: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver – mcbex Feb 07 '14 at 02:20
  • why not call it in ajax callback ? – Yukulélé Feb 07 '14 at 02:43
  • Event delegation should work fine. – Felix Kling Feb 07 '14 at 02:51

2 Answers2

1

If you're trying to hide the div with a button after it has been populated, you can add a listener to a parent element that already exists.

$('.parent').on('click','#foobar',removeFoobarFunction);

If you need to remove the div immediately, when it is populated, then you should use the ajax success callback like mcbex mentioned.

Read up on event delegation if you haven't:

https://learn.jquery.com/events/event-delegation/

Scott Hillson
  • 900
  • 1
  • 12
  • 30
0

You should create function then when creating the element add the function name into the element's onclick attribute.

//<div id="futureButton" onclick="onClickFunc"></div>
function onClickFunc(e){ alert("You clicked the future button"); }
mois
  • 119
  • 6