'How to toggle between two images on click without using JavaScript
In a HTML document, I have <img src="cat-thumbnail.jpg">
. When the user clicks on the image, I want to display another image instead: <img src="cat-full.jpg">
. The user should be able to toggle between these two images by clicking on the image. Is it possible to do this without using JavaScript? If so, how?
EDIT:
This is the HTML document in question:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Cat image</h1>
<img src="cat-thumbnail.jpg">
<!-- <img src="cat-full.jpg"> -->
</body>
</html>
Solution 1:[1]
I have found a solution that works without JavaScript:
HTML:
<label>
<input class="image-toggler" type="checkbox">
<img class="thumbnail" src="cat-thumbnail.jpg">
<img class="full" src="cat-full.jpg" loading="lazy">
</label>
CSS:
/* Hide checkbox */
input.image-toggler {
display: none;
}
/* When checkbox is unchecked, show thumbnail and hide full image */
img.full {
display: none;
}
/* When checkbox is checked, hide thumbnail and show full image */
input.image-toggler:checked + img.thumbnail {
display: none;
}
input.image-toggler:checked + img.thumbnail + img.full {
display: block;
}
This shows the thumbnail when the hidden checkbox is unchecked, and shows the full image when the hidden checkbox is checked. loading="lazy"
is for delaying the loading of the full image until the user needs it, but it is not a standard attribute.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |