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;

Andrei Surdu
  • 2,281
  • 3
  • 23
  • 32

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
  • 143,310
  • 32
  • 282
  • 281
0

You should use event delegation:

$('.block').on('click', '.elem', function(){
  $('.result').show().fadeOut('slow');
});
Andy
  • 61,948
  • 13
  • 68
  • 95