1

HTML

<div id='story'>    
    <div class='item folder'>sky</div>
    <div class='item folder'>sea</div> 
</div>

JS

$(".item").on('click', function(){
    $('.marked').removeClass('marked');
    $(this).addClass('marked');
});

This works but now the the content of #story is replaced using ajax procedure:

...    
success: function(data) {
    $('#story').html(data);
}

And the new content is:

<div class='item folder'>earth</div>
<div class='item folder'>venus</div> 

And here on('click', function() doesn't work. Classes are not removed/added.

jean-max
  • 1,640
  • 1
  • 18
  • 33
qadenza
  • 9,025
  • 18
  • 73
  • 126

3 Answers3

3

Event delegation does the trick:

$('body').on('click', '.item', function(){
    $('.marked').removeClass('marked');
    $(this).addClass('marked');
});
RWAM
  • 6,760
  • 3
  • 32
  • 45
2

Use event delegation for dinamically added elements:

$(document).on('click', '.item', function(){
    $('.marked').removeClass('marked');
    $(this).addClass('marked');
});

You can read more here.

Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
0

Click binding only work for html elements, which are available in the DOM at the time click is called. You have to bind a new click listener after you add something to the DOM.

ppasler
  • 3,579
  • 5
  • 31
  • 51