Adam Skiba
Adam Skiba

Reputation: 633

jQuery click() event not firing on AJAX loaded HTML elements

the subject is pretty descriptive of my problem, I am assuming it won't work this way, is there a way to make it work? (workaround)?

Here is the code that is loaded via AJAX:

<div>
<div id="s0frame" class="sframe"></div>
<div id="s1frame" class="sframe"></div>
<div id="s2frame" class="sframe"></div>
<div id="s3frame" class="sframe"></div>
<div id="s4frame" class="sframe"></div>
<div id="s5frame" class="sframe"></div>
<div id="chatframe" class="chat alpha60"></div>
</div>

Here is my click event:

$('.sframe').bind('click', function() { 
    var seat_number = this.id.match(/\d/g);
    alert(seat_number); 
});

Upvotes: 37

Views: 53554

Answers (4)

areeb
areeb

Reputation: 422

$(document).on('click','sframe', function() { 
    var seat_number = this.id.match(/\d/g);
    alert(seat_number); 
});

Upvotes: 2

Ajeet  Sinha
Ajeet Sinha

Reputation: 2345

Do this.

 $(document).on("click",".sframe",function(e){
 var seat_number = this.id.match(/\d/g);
 alert(seat_number); 
 });

or

 $(document).delegate(".sframe","click",function(e){
 var seat_number = this.id.match(/\d/g);
 alert(seat_number); 

 });

Edit:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate().

Upvotes: 90

Rafay
Rafay

Reputation: 31043

you have to re-attach the event handlers to the dynamically added elements into the DOM. .live method was used widely but now its deprecated. In jQuery version 1.7+ you can use .on or alternatively you can use .delegate

$(document).on("click",".sframe",function(e){

});

using delegate

$(document).delegate(".sframe","click",function(e){

});

Upvotes: 16

Aaron
Aaron

Reputation: 4614

Unless you are calling that .bind() function after that markup is loaded onto the page, you need to use another function like .live() or preferably if using a recent version of jQuery, .on() because .bind() only targets DOM elements already present when run whereas .live() and .on() give you different scope options for keeping track of elements added to the page.

Upvotes: 4

Related Questions