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.
if (test_src == null)instead ofif (test_src == undefined)imgtags? Can you store the number in theidattribute? I can think of some much simpler ways if you initially had e.g.<img id="12345" class="class" src="/images/12345.jpg">