4

Could any one explain me, why does a click event is not triggered, when an element is inserted in the dom from a variable

Consider

HTML

<div id="disp"></div>
<input type="button" value="clickme" id="cme"/>

jQuery

$("#cme").click(function(){
    var inside = '<input type="button" value="clickme again" id="sme"/>';
    $("#disp").html(inside);
});

$("#sme").click(function(){
    alert("clicked me");  
});

When you click clickme button, new button clickme again is added inside the disp and when clickme again button is clicked, it does not fire the click event attached to it. it does not alert clicked me ? why ?

But when I have tried this way, it works

$("#cme").click(function(){
    var inside = '<input type="button" value="clickme again" id="sme"/>';
    $("#disp").html(inside);
    // when i put here , it works
    $("#sme").click(function(){
        alert("clicked me");  
    });
});

I want to put the $("#sme").click outside. Any help is greatly appreciated. Thanks

user3205479
  • 1,443
  • 1
  • 17
  • 41

2 Answers2

2

You need to use Event Delegation

Use .on()

$("#disp").on('click', "#sme", function(){
    //Your code
    alert("clicked me"); 
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
2

try something like this

$("#disp").on('click', "#sme", function(){
    alert("clicked me"); 
});

Reason

you are applying click event on the element which is not present in DOM. so use on() jQuery function

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40