0

I am trying to change the opacity of an element after every 100 milliseconds after a click event. But it is not working. The function change is called after a click event. Here is my code:

function change (i) {
  var o:number = 0;
  setTimeout( function() {
    o = o + 0.1;
    document.querySelector("div.label").style.opacity = o;
    console.log("o = " + o);
  }, 100)
}

When I console log, the value of o is always 0.1. What is wrong with this code?

6
  • 1
    It looks like you're using typescript, should that tag be added? Also, do not use document.querySelector("div.label") with react. Prefer the use of ref and useEffect (or maybe useLayoutEffect) Commented Nov 2, 2021 at 11:33
  • Ok. But is there any javascript solution for this? Commented Nov 2, 2021 at 11:35
  • 1
    You are initializing the o variable inside the change function. Everytime you call it, o goes back to 0 and 0.1 after the timeout. And directly accessing the DOM isn't the way to go with React. Commented Nov 2, 2021 at 11:36
  • You can check Framer Motion if you're interested. Commented Nov 2, 2021 at 11:40
  • This question really needs some context of the surrounding React component. The code included heavily leads answerers towards solutions that wouldn't work well in the (not obvious) React setting. Commented Nov 2, 2021 at 11:47

2 Answers 2

1

You need to update the var o with the current opacity before increasing it:

function change (i) {
  var o:number = 0;
  setTimeout( function() {
    o = document.querySelector("div.label").style.opacity; // <-- ADD THIS
    o = o + 0.1;
    document.querySelector("div.label").style.opacity = o;
    console.log("o = " + o);
  }, 100)
}
Sign up to request clarification or add additional context in comments.

2 Comments

What if the component re-renders? It will start all over again
In that case the var o need to be initialized outside the component and there is no need to set it equal to the current opacity
0

You're using setTimeout(), but I think you're looking for setInterval() method (if you want something to repeat itself).

Try :

function change (i) {
  var o:number = 0;
  setInterval( function() {
    o = o + 0.1;
    document.querySelector("div.label").style.opacity = o;
    console.log("o = " + o);
  }, 100)
}

BE CAREFUL : you have to prevent your variable o to go beyond 1 (maximum opacity). You can use clearInterval().

3 Comments

What did you change here?
I used the setInterval() method instead of setTimeout()
Somehow I managed to do it. I also changed opacity = o to opacity = o.toString().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.