I’m trying to trigger a click event on a dynamically created element. I have used .on() to bind the click events, but it seems that the trigger method is firing before the element is created. I have tried triggering the click in several locations and nothing seems to work. Any help would be appreciated. I’m trying to trigger a click on the first span that is created using $(‘container:first-child’).trigger(‘click’);
displayThumbnails = function() {
$(photoArray).each(function(index) {
var thumbnailImg = this.SmallImageUrl,
largeImg = this.LargeImageUrl,
thumbnailId = 'thumbnail' + index,
largeImgId = 'image' + index;
if(index > indexCount) {
return false;
} else if (index >= indexStartValue && index <= indexCount) {
$(thumbContainer).append(
'<span class="thumbnail" id="' + thumbnailId + '"><img height="45px" width="60px" src="' + thumbnailImg + '"/></span>'
);
$(thumbContainer).on('click', '#' + thumbnailId, function(){
$(thumbContainer).find('.active').removeClass('active');
$(this).addClass('active');
$('#displayed-image').attr('src', largeImg);
});
}
});
};
Months later, I’m revisiting this. The answer IMO these days is that triggering a click in order to have a subsequent function call is too interdependent. If you are trying to trigger a click to make something happen on your page, you are probably thinking about it the wrong way. I ended up rethinking this and had a function that handled loading the large image on its own. Basically, I was trying to trigger the click to load an image.
By rethinking the process, I ended up with much cleaner code – everything working independently to handle a small function.
Also, the reason that I never accepted the other two answers is that .on() is the way to go for binding event handlers in jQuery as of 1.7.1.