With the power of jQuery, a multitude of features are automatically provided, making it challenging to replicate its functionality entirely. An example is demonstrated below, where all images with the class thumbnail
have their onclick
property set to trigger an image swap event handler.
onload = function () {
var bigImg = document.getElementById("mainImage");
for (var i = 0; i < document.images.length; i++) {
var img = document.images[i];
if (/\bthumbnail\b/.test(img.className) {
img.onclick = thumbnailHandler;
}
}
function thumbnailHandler(e) {
bigImg.src = this.src;
}
};
If IE7 support is not required, you can opt for a simpler implementation using document.querySelectorAll()
:
onload = function () {
var bigImg = document.getElementById("mainImage");
var thumbs = document.querySelectorAll(".thumbnail");
for (var i = 0; i < thumbs.length; i++) {
thumbs[i].onclick = thumbnailHandler;
}
function thumbnailHandler(e) {
bigImg.src = this.src;
}
};
Moreover, the rationale behind setting the main image's source as the thumbnail's source may be questioned. Is the full image being loaded into the thumbnail? This practice could lead to excessive downloads and escalate the page's memory consumption rapidly.