I have a div that is loaded dynamically with one or more images. Initially, all these images are crops. The aim is, when a when a user clicks on a cropped image, its src is replaced by the full sized version. Click the full sized version to return to the cropped image. I have no knowledge of the file names of the image, other than that they are all numbers, except the full version has a "L" as the first character in the file name.
This code works, but I'm sure there must be a simpler way:
$('#class').on('click', '> img', function() {
var src = $(this).attr('src');
var test_src = src.match(/L/g);
var img_id = src.replace(/L/g, '');
var big_img = src.replace('/images/', '/images/L');
if (test_src == undefined) {
$(this).attr('src', big_img)
} else {
$(this).attr('src', img_id);
}
});
The problem I only managed to overcome with this code was, if I simply got the img src and added an 'L', after the first click, the img src was changed to something like '/images/L123345.jpg', and so, clicking it again with the aim of returning to the original src ('/images/12345.jpg') just added a second L.
I'm sure I've missed something really obvious. Thanks for any suggestions.
When you can add other attributes to your images, one option is to store the base image filenames in either the
id
, or in adata-*
attribute if you're using HTML5. With images such asthe following function will build a new
src
attribute required to swap the size from its current value. It does this first by retrieving the ID, then defining a variablelg
that is an empty string if the current source includes an 'L', and equal to 'L' otherwise. Finally, it strings the two together, along with the path and file extension.You could try using jQuery class methods. Not sure if it's simpler, but I find it easier to read.
This might work...