Jquery click doesn't work on html created by ajax

I've created a page that has a empty div#info which is filled with html from an ajax request. The request gets a list of spans from another page, which is put in the div. Now if I try to use a jquery click function on those spans, nothing happens. It took me some time to realise that this is newly created html. It looks like Jquery is not aware of the new html?

How can I get this working?
LVL 13
R7AFAsked:
Who is Participating?
 
Chris StanyonConnect With a Mentor Commented:
Yeah, sonawanekiran is correct, you need to use the on() function. If your version of jQuery is less than 1.7 then you use delegate() instead.

http://api.jquery.com/on/
$("#info").on("click", "span", function(){
      alert("Clicked");
});

http://api.jquery.com/delegate/
$('#info').delegate("span", "click", function(){
     alert("Clicked");
}
0
 
Kiran SonawaneConnect With a Mentor Project LeadCommented:
Since you html is loaded dynamically. You should handle the click event like this..

$("#your_selector").on("click", "tr", function(){
      alert($(this).html());
});
0
 
Roger BaklundCommented:
Either use delegated events as described above, or set the event handlers after the HTML is loaded:

LoadHTMLWithAJAX();
// '#info span' exists now
$('#info span').click( ... );

Open in new window

0
 
Andrew DerseIT ManagerCommented:
Or you can simply call a new on click function after your ajax loads...

for example...basic logic only here...
function getSpanClick() {
  //get click param after ajax is loaded...
}

function ajaxCall() {
  // get information...
  // write information...
  // call next function...  
  getSpanClick();
}

Open in new window


This method works 100% of the time...everytime...I've been using it ever since I've been developing with jQuery.
0
 
R7AFAuthor Commented:
Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.