0

How can I run the jQuery script for new created DOM elements? Look at the following code, if I click the class .elem it will run the code, but if I append new .elem the script won't run.

JS:

$('.elem').on('click', function(){
    $('.result').show().fadeOut('slow');
});
$('.add').on('click', function(){
    $('.block').append('<div class="elem">Element</div>');
});

HTML:

<div class="block">
    <div class="elem">Element</div>
    <div class="elem">Element</div>
    <div class="elem">Element</div>
</div>

<p><span class="add">Add new</span></p>

<div class="result">Result</div>

JSFiddle here: http://jsfiddle.net/3Y3Cn/3/

Any help is hightly appreciated. Thanks you;

Andrew Surdu
  • 2,118
  • 2
  • 18
  • 31

2 Answers2

3

Use event delegation with any static parent element:

$('.block').on('click', '.elem', function() {
    $('.result').show().fadeOut('slow');
});

DEMO: http://jsfiddle.net/3Y3Cn/4/

VisioN
  • 132,029
  • 27
  • 254
  • 262
0

You should use event delegation:

$('.block').on('click', '.elem', function(){
  $('.result').show().fadeOut('slow');
});
Andy
  • 39,764
  • 8
  • 53
  • 80