So basically I wanted to alter the opacity of an element in a grid using an event listener. In this event listener I would get the opacity of the element and increment it by 0.1. I used to do this using the following code:
square.addEventListener("mouseover", function (e) {
let opacity = e.target.style.opacity;
if (opacity + 0.1 < 1) {
e.target.style.opacity = opacity + 0.1;
} else if (opacity + 0.1 >= 1) {
e.target.style.opacity = 1;
}
});
Where square
stands for the following
const cont = document.querySelector(".cont");
const square = document.createElement("div");
And then I append the square
.
cont.appendChild(square);
Well, the problem I have could be described as follows. The opacity is only incremented to 0.1 and if you hover again over the square element the opacity is 0.1 every time, it will never increase. I have the theory that the opacity of the div element is in each iteration initialized to 0. This suspicion arises when I thought about this problem but it looks confirmed by a very nice solution I came across Reddit
square.addEventListener("mouseover", function (e) {
let opacity = e.target.style.opacity;
if (opacity) {
e.target.style.opacity = Number(opacity) + 0.1 ;
} else {
e.target.style.opacity = 0.1;
}});
This seems to look for a truthy value in the content of the opacity.
3
Answers
when you retrieve the style it is coming back as a string (see my demo) so when you compare it to 0.1 it’s not working correctly. What you need to do is to use
parseFloat(e.target.style.opacity)
Sometimes you may need to retrieve the element style using
getComputedStyle()
.The magic in your Reddit answer does not lie in the if statement but in the use of
Number
because all attributes with values are strings. So you need to convert the string into a number.