So far I used a no-javascript way to toggle an image from compressed to expanded, using input and label tags. That solution works, but I think that from a semantic point of view it is not correct. In other words it’s just a trick.
So I wonder if there is a jquery (or vanilla js) solution to toggle an image size, using css max-width.
My css should be:
normally img size: max-width: 10vw
expanded size: max-width: none;
What code should I write to get the image expanded by clicking it?
The script is in the head which is encountered before the body and as such your image does not exist yet so nothing is found. Move the script to before the closing body tag so that the page has loaded before the script fires.
<body>
<img src="http://localhost/mypath/myfile.jpg" class="image image-small" />
<script">
//expand image al posto di label e input
document.querySelectorAll('.image').forEach(imageElement => {
imageElement.addEventListener('click', e => {
e.preventDefault()
imageElement.classList.toggle('image-small')
})
})
</script>
</body>
</html>
OK, I understand this.
I’m not able to explain , but that two classes bother me, because it seems not enough “semantic”.
So I have modified your code as following:
<html>
<head>
<style type="text/css">
p {text-align: justify;}
body {margin-left: 5px; margin-right: 5px; font-family: sans-serif, ubuntu, arial;}
.image {
cursor:pointer;
}
.image-small {
max-width: 20vw;
}
</style>
</head>
<body>
<img src="http://localhost/imypath/myimage.jpg" class="image-small" />
<script type="text/javascript">
//expand image al posto di label e input
document.querySelectorAll('img').forEach(imageElement => {
imageElement.addEventListener('click', e => {
e.preventDefault()
imageElement.classList.toggle('image-small')
})
})
//-->
</script>
</body>
</html>
Well you’re free to rename those classes to make them more semantic. For example,
<img class="clickable thumbnail" ... >
Usually it is very bad idea to bind events by tag name, because later you’ll decide to add other type of image to the page (say, ad banner) which shouldn’t react on clicks in the same way as your thumbnails