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
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.

$("#info").on("click", "span", function(){

$('#info').delegate("span", "click", function(){
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(){
Roger BaklundCommented:
Either use delegated events as described above, or set the event handlers after the HTML is loaded:

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

Open in new window

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...  

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.
R7AFAuthor Commented:
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.