sam sam - 4 months ago 8
jQuery Question

can't get click event of div element in jquery

This problem is so weird and the title might not seem to fully explain the meaning, so this is what i mean, i have list of div nested in each other and i can get the click event and other event of the outer Div but can't get the click event and other event of the inner div and it's content. below is my code

var scrollWidth = 124;
var currentPhoto;
var defaultDisplayPhoto = 5;
var maxScrollCount=0;
var maxScroll =(scrollWidth*currentPhoto)-(scrollWidth*defaultDisplayPhoto);
var maxScroll;
var timeCounter;
var duration = 1000; //time to wait to fire the event;
var photoAllowed = 12;
var canAddMore;

var eventCounter= [];
$("input.upload").on('change',function(event){
$(".mycarousel-container").show();
if(eventCounter){
i=eventCounter.length;
}else{
i=0;
}
imgsrc = URL.createObjectURL(event.target.files[0]);
//for(var i=0; i <eventCounter.length; i++)
var div = $("<div class='mycarousel' style='left:"+left+"px' id='picture"+i+"'></div>");
var transparentDiv = $("<div class='transparent'></div>");
var deleteIcon = $("<span class=\"deletebutton\"><i class=\"glyphicon glyphicon-trash\"></i></span>");
var imgPreview = "<img class='myimg' src="+imgsrc+">"
transparentDiv = transparentDiv.html(deleteIcon);
div = div.html(transparentDiv);
div = div.append(imgPreview);
$(".carouser-inner").append(div);

left = left+120;

eventCounter.push(imgsrc);
if(eventCounter.length>5){
$("#carousel_control_left").show();
$("#carousel_control_left").addClass('myActive');
scrollThumb('Go_R');
}else{
$("#carousel_control_left,#carousel_control_right").hide();
}

if(eventCounter.length == 12){
alert('end')
$("input.upload").attr('disabled',true);
}else{
$("input.upload").attr('disabled',false);
}

});


$('.mycarousel').click(function(){
alert('this is inner div with border color blue');
});
$('.myimg').click(function(){
alert('this is inner image');
});


DEMO ON FIDDLE
please see the demo on fiddle and add some images and divs will show up, now try to get the click event of the div with border color BLUE or the image in it

Answer

use $(document).on cause when you assign your click event , div element is not in DOM yet

 $(document).on( 'click', '.mycarousel', function () {
        alert("here");
   });