0

I have a simple example

    <div id="test">add more text</div>

When you click on this text

    jQuery('#test').on('click', function (event) {
        $('body').append("<div id='newtest'>new test</div>");
    });

you get some more text appear. After I have clicked on 'add more text' my page looks like this

<div id="test">add more text</div>
<div id="newtest">new test</div>

I am wondering what I need to do to interact with the newtest div?

If I put the below in.

jQuery('#newtest').on('click', function (event) {
    alert('not working?');
});

Nothing happens. How do I interact with content that gets added after load? I thought .on helped me do this?

ak85
  • 3,920
  • 16
  • 61
  • 110

4 Answers4

3

The reason why you need to use $(document).on() instead of $('#newtest').on() is because #newtest is a new element that you have injected into the DOM.

You must now use .on() ) against an higher element that was originally in the DOM, in order to attach an event handler to the newly injected element.

Thus:

jQuery(document).on('click', '#newtest', function (event) {
    alert('This will work now');
});
cssyphus
  • 34,778
  • 18
  • 87
  • 102
1

You need to apply your click handler to the document.

jQuery(document).on('click', '#newtest', function (event) {
    alert('not working?');
});

Hope this helps! :)

wrxsti
  • 3,289
  • 1
  • 16
  • 29
1

put the event on your document instead of an element

jQuery(document).on('click', '#newtest', function (event) {
    alert('not working?');
});
Gotschi
  • 3,165
  • 2
  • 23
  • 21
0

Set the .on() event to a parent element, such as the body and delegate it to the newtest div.

jQuery('body').on('click', '#newtest', function (event) {
    alert('Working!');
});
Nagendra Rao
  • 6,716
  • 5
  • 48
  • 88
HaukurHaf
  • 12,968
  • 5
  • 40
  • 56