After append() how to bind a click event to just added element

10,004

Solution 1

well you can just rebind it with the same click function you have used before or you use .live() http://api.jquery.com/live/

Solution 2

Replace

$(".delete2").click(function() {
    $('#load2').fadeIn();
}

with

$(".delete2").live('click', function() {
    $('#load2').fadeIn();
});

This way the click event is bound to all existing an in the future created elements with class .delete2

Solution 3

$(<parent selector>).on('click', '.delete2', function() { alert('test'); });

Change the parent selector to the id or class of the parent element

Share:
10,004
Pentium10
Author by

Pentium10

Backend engineer, team leader, Google Developer Expert in Cloud, scalability, APIs, BigQuery, mentor, consultant. To contact: message me under my username at gm ail https://kodokmarton.com

Updated on June 04, 2022

Comments

  • Pentium10
    Pentium10 almost 2 years

    I have this code

    $(".delete2").click(function() {
      $('#load2').fadeIn();
    }
    

    I have dynamically added item via this return

    addSubcategory = function(){
            sucategorynameval = $("#sucategoryname").val(); 
            categoryId        = $("#addcategoryid").val(); 
            $.get("process-add-subcat.php", { "action": "add_subcategory", "sucategoryname": sucategorynameval, "categoryId":categoryId },
                   function(data){
                     //$("#main-cat-"+categoryId).load(location.href+"&pageExclusive=1 #main-cat-"+categoryId+">*","");
                     $("#main-cat-"+categoryId).append(data);
                     $("#addcategoryid").val(''); 
                     $("#sucategoryname").val(''); 
                   }); 
    

    The returned data contains delete2 classed item.

    How do I apply the click event to the newly added item?

  • Craig Myles
    Craig Myles about 11 years
    As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). See api.jquery.com/live
  • makciook
    makciook almost 11 years
    This code is not an answer to Pentium10 question. Please describe and give the proper code