2

I have a couple of Divs in my page with CSS class="hello" Further I use Ajax to fetch a few more Divs with a CSS class="hello" I have a piece of code which is called on Click event of the Divs as follows:

$('.hello').click(function(){
  alert("Hello Clicked");
})

It works fine with the Divs that are present in my page from start but does not work with Divs loaded using Ajax. Is there something I need do in order to bind this little piece of code with the newly loaded Divs too?

Joseph
  • 117,725
  • 30
  • 181
  • 234
Raouf Athar
  • 1,803
  • 2
  • 16
  • 30

1 Answers1

8

you should use .on to bind the handler to another element that is already present during the execution of the binding, like say the <body>, or the document and have it detect the children events. but ideally, you should bind it to the nearest common parent of the content loaded.

demo

//bind to the body a "click" handler for elements that have class names of "hello"
$('body').on('click','.hello',function(){
  alert("Hello Clicked");
})
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • I got an error TypeError: Object [object Object] has no method 'on'. My guess was I am using older version of JQuery and I was right. I upgraded from 1.6.2 to 1.7.2 and now it works. Thanks. – Raouf Athar Apr 12 '12 at 01:42