Handle click event for appended elements in jQuery

49,398

Solution 1

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!");
}); 

Solution 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/

Share:
49,398
Eddard Stark
Author by

Eddard Stark

Updated on March 28, 2020

Comments

  • Eddard Stark
    Eddard Stark about 4 years

    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.