Reputation: 2126
I have created a script that creates divs based on number of li elements and that part is working fine. Now what I would like to do is to hide these div's (dynamicly created) but it is not working. Can someone tell me what I am doing wrong here? THX!!
Fiddle here
My code:
$(document).ready(function(){
$(".create").click(function(){
i='';
var count = $("li").length;
for(var i=0;i<count;i++){
$('<div class="mydiv" style="width:100px;height:100px;background-color:red;border:1px solid #000000;"></div>').appendTo('body');
}
});
$('.check').click(function(){
var getDivs= $('div').length;
alert(getDivs);
});
//Why is this not working?
$('div').click(function(){
$(this).hide();
});
});
Upvotes: 2
Views: 62
Reputation: 104775
Try
$(document).on('click', 'div', function () {
$(this).hide();
)};
Upvotes: 0
Reputation: 3695
All of this code should be in jQuery ready. The problem is your events are being bound before the elements have been created.
$(document).ready(function(){
$(".create").click(function(){
i='';
var count = $("li").length;
for(var i=0;i<count;i++){
$('<div class="mydiv" style="width:100px;height:100px;background-color:red;border:1px solid #000000;"></div>').appendTo('body');
}
$('.check').click(function(){
var getDivs= $('div').length;
alert(getDivs);
});
//Now working
$('div').click(function(){
$(this).hide();
});
});
});
Upvotes: 1
Reputation: 82267
Try to do this instead (and attach the click event when you create the div):
$('<div class="mydiv" style="width:100px;height:100px;background-color:red;border:1px solid #000000;"></div>')
.click(function(){
$(this).hide();
})
.appendTo('body');
Upvotes: 3