skip to Main Content

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


  1. 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)

    document.querySelector("P").addEventListener("mouseenter", (e) => {
      console.log("here: " + typeof e.target.style.opacity);
    });
    p {
      opacity: 0.5;
    }
    <p>Test</p>
    Login or Signup to reply.
  2. Sometimes you may need to retrieve the element style using getComputedStyle().

        square = document.querySelector(".square")
        square.addEventListener("mouseover", function (e) {
                let opacity = parseFloat(getComputedStyle(e.target).opacity);
                e.target.style.opacity = (opacity + 0.1) < 1 ? opacity+=0.1 : opacity = 1;
            });
    .square{
      background-color: aliceblue; 
      width: 100px; height: 100px; 
      opacity: 0.1;
    }
    <div class="square"></div>
    Login or Signup to reply.
  3. 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.

    document.querySelector("p").addEventListener("mouseenter", (e) => {
      e.target.style.opacity = Number(e.target.style.opacity) + 0.1;
    });
    p {
      opacity: 0.1;
    }
    <p>Test</p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search