Home > Back-end >  how do i increase opacity for every clcik
how do i increase opacity for every clcik

Time:11-06

i am tryng to make an IF function for a value of opacity and then divide it by 10 to get a decimal in a range between (0.0 to 0.9), the function works when there is no value (!e.target.style.opacity) and when opacityValue gets to 9; but then it gets stucked in 8, i wnat to trigger that event as long as opacity dont get to 0;

function toEternalDarkness(e) {
    let opacityValue = 9;
    let opacityDegree; 
    if (!e.target.style.opacity) {     
        opacityDegree = opacityValue / 10;   
        e.target.style.opacity = opacityDegree;
        console.log(opacityValue);
    } else if (e.target.style.opacity !== 0) {
        opacityValue--;
        opacityDegree = opacityValue / 10;
        console.log(opacityDegree);
        e.target.style.opacity = opacityDegree;        
    } else {return}

i tryed to declare the opacityDegree inside the iIF statement and it didnt work
i tryed to declare a new variable to store newOpacityValue and didnt work
i tryed a while loop inside the IF ELSE statement and it runs all the loop until opacity gets to zero

CodePudding user response:

Dividing by 10 every time will make it go invisible really fast. Does this work for you?

const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
  if (!btn.style.opacity) btn.style.opacity = '1';
  opacity = parseFloat(btn.style.opacity);
  btn.style.opacity = opacity - 0.2;
});
<button id="btn">Click Me</button>

CodePudding user response:

You can decrement the value within the division opacityValue-- / 10 return the results of a conditional. Since you are using a number type variable to decrement the value by 10, there is no need to parseInt.

The snippit show cases a div with a white background and with each click the elements opacity style is decremented by the calculation => opacityValue-- / 10.

let opacityValue = 9;

function toEternalDarkness(e) {
  return !e.target.style.opacity ? e.target.style.opacity = opacityValue-- / 10 : e.target.style.opacity = opacityValue-- / 10
}

document.querySelector('.cont').addEventListener('click', toEternalDarkness)
body {
  background-color: black;
  margin: 0;
  padding: 0;
}

.cont {
  background-color: white;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: sans-serif;
}
<div >
  Click Anywhere To Reduce The Opacity Of This Element
</div>

  • Related