I’m trying to make an item tracker for a game as a webapp. I wanted to have the icon of each item displayed in a grid, and when you click on the image it darkens to indicate that you’ve gotten it. So far I’ve only figured out how to affect the opacity of the images, but works well enough for now. Though when the opacity starts at 1.0, it requires a second click to activate, but only for the first time. After that it works as intended, toggling on click. If I set the initial opacity to 0.5, it works on the first click.
I made a table to place the images in a grid (added 8 for the time being) and gave each one a unique id, and the class “Loot” like so:
function lootDarken(x) {
image = document.getElementById(x);
if (image.style.opacity === "1") {
image.style.opacity = "0.5";
} else {
image.style.opacity = "1";
}
}
<table>
<tr>
<td><img onClick="lootDarken('Loot1')" id="Loot1" class="Loot" src="https://picsum.photos/200/300"></td>
<td><img onClick="lootDarken('Loot2')" id="Loot2" class="Loot" src="https://picsum.photos/200/300"></td>
<td><img onClick="lootDarken('Loot3')" id="Loot3" class="Loot" src="https://picsum.photos/200/300"></td>
<td><img onClick="lootDarken('Loot4')" id="Loot4" class="Loot" src="https://picsum.photos/200/300"></td>
<td><img onClick="lootDarken('Loot5')" id="Loot5" class="Loot" src="https://picsum.photos/200/300"></td>
<td><img onClick="lootDarken('Loot6')" id="Loot6" class="Loot" src="https://picsum.photos/200/300"></td>
<td><img onClick="lootDarken('Loot7')" id="Loot7" class="Loot" src="https://picsum.photos/200/300"></td>
<td><img onClick="lootDarken('Loot8')" id="Loot8" class="Loot" src="https://picsum.photos/200/300"></td>
</tr>
</table>
Also, if there’s a cleaner/easier way to place these images in a grid, please share. I have to go through hundreds of these.
I thought maybe it was because the opacity wasn’t officially set, and that clicking it the first only set the opacity to 1 since technically, the opacity wasn’t 1. So I added the class “Loot” in order to set the opacity on startup. That didn’t work, so I tried setting the initial opacity to 0.5 just to see what would happen and that worked wonderfully.
I also tried reversing the function, making it check if the opacity is not 1:
function lootDarken(x) {
image = document.getElementById(x);
if (image.style.opacity != "1") {
image.style.opacity = "1";
} else {
image.style.opacity = "0.5";
}
}
But that led to the same result. I don’t even know what is happening that’s causing this weird interaction, so I came here hoping for an explanation… and maybe tips on how to make it less repetitive.