sam sam - 1 year ago 58
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= [];
imgsrc = URL.createObjectURL([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);

left = left+120;


if(eventCounter.length == 12){


alert('this is inner div with border color blue');
alert('this is inner image');

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 Source

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

 $(document).on( 'click', '.mycarousel', function () {