Abuda Dumiaty
Abuda Dumiaty

Reputation: 317

Later-inserted tags not seen by JQuery

Say I have this code in my page:

<script language="javascript">
 $(document).ready(function() {
  $(".test").click(function() {
   alert('Hello');
  });
 });
</script>

Why doesn't the previous code apply to elements with the class "test" which I add later to the document like this for example:

$('body').append('<p class="test">Test</p>');

Because what happens is that when I click the previous <p> tag nothing happens.

Also, if I have this:

<div id="first">Edit me.<div id="second">Save me.</div></div>

Can I do what the text describes? that is, controlling the content of the #first div without affecting the content of the #second div?

Thank you.

Upvotes: 1

Views: 172

Answers (7)

bart s
bart s

Reputation: 5100

If you need to apply the click to later added tags, you should use live on

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

EDIT: @Anthony your're right. live is deprecated. Updated the code

Upvotes: -2

eyurdakul
eyurdakul

Reputation: 912

you should use "on" to bind events with the elements that are added after the script is interpreted.

$(document).on("click", selector, function(e){
    //do something
});

Upvotes: -1

Willem D&#39;Haeseleer
Willem D&#39;Haeseleer

Reputation: 20180

live is deprecated as of 1.7, use on

http://api.jquery.com/on/

Upvotes: 3

Dan Blows
Dan Blows

Reputation: 21174

When you bind events to elements they only bind to those elements that have already been created. So you need to run the 'bind' command again on the new elements.

Alternatively, you can use on('click') which will bind the event to existing and all future elements.

Upvotes: 1

Elen
Elen

Reputation: 2343

try using on() listener:

$(document).on("click",".test", function() {

  alert('Hello');

});

Upvotes: 2

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

The problem is that .click() does only apply a listener for elements that are available in the DOM when the method is executed. You should take a look at .on() instead.

With .on() you can delegate the event, like this for instance:

$("body").on("click", ".test", function() {
   alert('Hello');
});

Now any element (current and future) with the class test available within your body will have a click-event listener.

Upvotes: 7

TJHeuvel
TJHeuvel

Reputation: 12608

Because at the time you attach your event handler the object doesnt exist yet. You cant subscribe to elements that dont exist. You can use the Live method for this. http://api.jquery.com/live/

It seems those are deprecated (thanks @Anthony Grist). Use On, or delegate() instead.

http://api.jquery.com/on/

http://api.jquery.com/delegate/

$('div').on('click', function()
{
 //Do something
});

Upvotes: 0

Related Questions