Dejo Dekic
Dejo Dekic

Reputation: 2126

How to hide my dynamicly created divs?

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

Answers (3)

tymeJV
tymeJV

Reputation: 104775

Try

$(document).on('click', 'div', function () {
 $(this).hide();
 )};

Upvotes: 0

VNO
VNO

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

Travis J
Travis J

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

Related Questions