jQuery: Bind Events To Dynamically Created Elements
by kavidha PR
HTML
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<h2>Click on a square</h2>
<div id="parent">
</div>
<h2>Child elements clicked</h2>
<div id="results">
</div>
<div style="position: absolute;bottom: 5px;">
Read about this Fiddle at: <a href="http://jsdev.wikidot.com/howto:1" target="_blank">How To: jQuery - Bind Events To Dynamically Created Elements</a>
</div>
CSS
div.child {
width: 50px;
height: 50px;
margin-right: 10px;
display: inline-block;
}
div.child:hover {
cursor: pointer;
}
#results {
min-height: 50px;
border: 1px solid lightgrey;
padding: 5px;
}
JavaScript
$(function () {
// Get the parent div.
var $parent = $("#parent");
var count = 1;
// Create click event handler on the parent div for the child div elements.
$parent.on("click", "div.child", function (event) {
// Get the color of the selected child div element.
var color = $(event.target).css("background-color");
// Write a message to the results div with the color of the child div element that was clicked.
$("#results").prepend("<div>" + count++ + ". You clicked on the child elemnt with a background-color of: " + color);
});
var colors = ["red", "green", "blue"];
// Add some child div elements to the container.
for (var idx = 0; idx < colors.length; idx++) {
var $div = $("<div></div>")
.addClass("child")
.css("background-color", colors[idx]);
$parent.append($div);
}
});