-3

I need my jquery .on to detect the newly added elements from .get.

simple scenario

$('.click').on('click',function(){
    alert('clicked');
});

<body>
    <div class='content'>
        <div class='click'>click here</div>
    </div>
</body>

it works fine for the above, but when i added a new

<div class='click'>click here</div>

by

$.get('url',function(data){
    $('.content').append(data);
});

the second click wont be detect by the jquery, only the first click is working. when i try to change to .live, its not working entirely.

any alternative way to make this works? thank you.

Ninjoe Quah
  • 289
  • 4
  • 22

4 Answers4

3

.live() is removed in 1.9 and deprecated in 1.7 use .on() instead, and delegate to the closest static parent element or document

$(document).on('click','.click',function(){
Anton
  • 30,499
  • 5
  • 42
  • 54
  • 1
    thanks, wasted whole day just to look for solutions. – Ninjoe Quah Jan 21 '14 at 09:29
  • 2
    @NinjoeQuah: Then you should _learn_ how to do some _proper_ research … even the [official docs for jQuery’s .on](http://api.jquery.com/on/) explain it already. – CBroe Jan 21 '14 at 09:46
2

You should use:

$(document).on(click, '.click', function(){
   alert('clicked');
} );
Milind Anantwar
  • 77,788
  • 22
  • 86
  • 114
1

You should bind the .on() to the document, as such:

$(document).on('click', '.classname', function() {
    // do something neat
});

That way, whenever a new element is added to the DOM, with a class of 'classname', it'll automatically receive that event listener.

-1

You are providing same class name for two divs which is wrong, in this condition only one click will work. so just provide the different class name in second div and bind one more click event with that class name then it will work. add like this.

$('.click2').on('click',function(){
    alert('clicked');
});

and HTML will be

<div class='click2'>click here</div>
Shivam
  • 692
  • 2
  • 10
  • 25