Shan Biswas Shan Biswas - 3 months ago 8
HTML Question

how to add callback function to elements which are added by JQuery

The callbacks functions are not working on the elements which are added by JQuery. Here in my example there is a parent div with

class=parent
. After clicking on it a
<span class="child">Child</span>
is being added. But when I am click on the the child it does not alert the message. Please see the example below

<html>
<head>
<style>
.parent{
width: 50px;
height: 30px;
line-height: 30px;
background-color: #232323;
color: #fff;
text-align: center;
}

.child{
width: 50px;
height: 30px;
line-height: 30px;
background-color: #f3b556;
color: #232323;
text-align: center;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="parent">
<span>Parent</span>
</div>


<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$('.parent').click(function(){
alert('parent clicked');
$(this).after("<span class='child'>child</span>");
});
$('.child').click(function(){
alert('child clicked');
});
</script>
</body>
</html>

Answer

Use a live delegation, because the .child is dynamic added element a normal event listener will not register the click on childs generated in the future.

$(body).on("click", ".child", function(){
    alert('child clicked');
});