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
  • 4,154
  • 18
  • 68
  • 113

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
  • 37,875
  • 18
  • 96
  • 111
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,434
  • 1
  • 18
  • 30
1

put the event on your document instead of an element

jQuery(document).on('click', '#newtest', function (event) {
    alert('not working?');
});
Gotschi
  • 3,175
  • 2
  • 24
  • 22
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
  • 7,016
  • 5
  • 54
  • 92
HaukurHaf
  • 13,522
  • 5
  • 44
  • 59