30

I have generated few elements in my page using following method. For example,

$("#button"+caption).click(function(){
        var firstDisplay = '<div id="firstDisp'+caption+'"><ul>';
        for(var i=0;i<parents.length;i++){
            firstDisplay=firstDisplay+'<li class="fClick">'+parents[i]+'</li>';
        }
        firstDisplay=firstDisplay+'</ul></div>';
        $(firstDisplay).dialog();
});

and when i create an onclick event for 'fClass' like so :

$(".fClick").click(function(){
    alert("hey!");
}); 

It does not works ! However, if i put the onclick function inside the other function, right after .dialog(), it works ! I have a lot of elements created this way, so I cannot put all onclick events in a single method. Is there any way around this? I am having the same problem with .append method as well.

Eddard Stark
  • 3,575
  • 8
  • 35
  • 51
  • possible duplicate of [jquery events doesn't work for appended elements](http://stackoverflow.com/questions/10856650/jquery-events-doesnt-work-for-appended-elements) – bfavaretto Aug 21 '12 at 13:08

5 Answers5

83

Change it to .on or .delegate based on the version of jQuery you are using..

As of jQuery 1.7+

$(document).on('click', '.fClick', function(){ 
    alert("hey!");
}); 

For older jQuery versions use delegate

$(document).delegate('.fClick', 'click', function(){
    alert("hey!");
}); 
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
2

Use on instead of click:

$(".fClick").on('click',function(){
  alert("hey!");
}); 

click adds click handlers to .fClick elements that are present when you call $('.fClick').click({...}). New .fClick elements added later won't have the click event. But when you use on, all .fClick elements will have a click handler, even if they are added later.
Read more here: http://api.jquery.com/on/

Abraham
  • 20,316
  • 7
  • 33
  • 39
0

call the $(document).ready(function() again and add your code there. The document gets read (refreshed) again and you can just apply your code there.

DenniZr
  • 43
  • 6
0

What Vega has said is completely working. There is a hint : I think in the second line there is a mistake. Probably you can use addClass method because you can't put id or class in rendering. Here is an example:

var content = "<div>Hello, World</div>";
$("div").after(content);
$("last:div").addClass("mydiv");

And the class will be added but I am not sure that you can add an id.

0

$('#element').append('Close');

$(document).on('click', '#close', function() {
      // This will work!
});
Evo
  • 1
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 23 '22 at 05:49