On this fiddle http://jsfiddle.net/adrianjsfiddlenetuser/zyUkd/46/ the divs ‘Hello 01’ & ‘Hello 02’ fire an alert when they are clicked. When i click ‘Add New’ a new div is added but when I click on this div the alert is not fired even though it is styled with same css .
How can I amend this so that the alert is fired when a new div is appended ?
Code from jsFiddle for posterity
JS
$(function() {
$(".myDivs").click(function() {
alert('Clicked');
});
$("#button").click(get);
function get() {
$(".connected").append("<div class=\"myDivs\">hello</div>");
}
});
HTML
<div class="connected">
<div class="myDivs">Hello 01</div>
<div class="myDivs">Hello 02</div>
</div>
<input name="Button3" type="button" value="Add New" id="button">
You need delegate event handler, because your way on bind event only bind event to existing DOM
.myDivs, but not for upcoming.DEMO
For more detail go here