Tag: js

Make image clickable without using jQuery

For a secondcrack blog I found myself needing to be able to make the images in the post clickable so that they could be opened in a bigger size. It was a simple use case, so I did not feel like including external libraries to accomplish this (jquery or other image libraries). As it turns out, all images are available via the document attribute images. The solution posted below iterates over all the images, filters them based on the fact that they have /media in the source (only those needed to be clickable) and sets an onclick event.

//open images in a new window
var images = document.images;
for(i = 0, imagesLength = images.length; i < imagesLength; i++) {
    if (images[i].src.indexOf('/media') !== -1) {
        images[i].setAttribute('onclick', 'window.location.href = \'' + images[i].src + '\';');
}
}

Leave a Comment