Reputation: 7164
I have 4 images on my webpage, when I click one of them, the clicked image is highlighted. I achieve using this :
JS1 :
var ImageSelector = function() {
var imgs = null;
var selImg = null;
return {
addImages: function(container) {
imgs = container.getElementsByTagName("img");
for(var i = 0, len = imgs.length; i < len; i++) {
var img = imgs[i];
img.className = "normal";
img.onclick = function() {
if(selImg) {
selImg.className = "normal";
}
this.className = "highlighted";
selImg = this;
urlSet(this.src);
};
}
}
};
}();
JS 2:
var div = document.getElementById("menu");
ImageSelector.addImages(div);
CSS :
.normal {
border:none;
}
.highlighted {
border:8px solid #19A3FF;
}
I have inserted a jQuery code that displays all images in a folder, which is this :
var dir = "images/";
var fileextension = ".jpg";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//Lsit all png file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location, "").replace("http://example.com/", "");
$(".menu").append($("<img src=" + dir + filename + " width=300 height=300>"));
});
}
});
HTML code is this :
<div>
<div id="menu" class = "menu">
</div></div>
When I inserted that jQuery code, the images are displayed but not clickable anymore. How can I make them clickable again? Thanks.
Upvotes: 2
Views: 84
Reputation: 1091
Mohit Arora - call your function ImageSelector in success event after append image or use delegation.
I'll explain why, It's because you set the .onclick function before the images are loaded. An ajax call is executed after your code because ajax is async. If you want to hook anything to something you called via ajax always do it in the succes event.
Upvotes: 3