Issue
Dears,
I want to create a fade out and resume effect in terms of the opacity of an element, below is my code:
function start() {
let abc = document.getElementById("myDIV");
abc.className = "class1"
const aa = document.querySelector(".class1");
setTimeout(function() {
if (aa.style.opacity === "0";) {
abc.className = "";
}
}, 2000);
}
.class1 {
background-color: coral;
padding: 16px;
opacity: 0;
transition: opacity 1s linear;
}
<div id="myDIV">
<p>I am myDIV.</p>
</div>
<p>Click the button to set a class for myDIV:</p>
<button onclick="start()">Try it</button>
The code ""abc.className = "class1" is for the fade out, I want the "myDIV" element to resume after fade out.
My thought is after the execution of the code "abc.className = "class1", the opacity of abc will be zero. In order to make sure the fade out is complete before it go to the next code, I apply a setTimeout code so that the code "if(aa.style.opacity ==="0";){abc.className = ""} is executed delayed by 2 seconds. However, I can't get the expected result, what's wrong in my above codes? Thanks.
Solution
- You have a semicolon where it does not belong
- You are selecting something by class, and then change the class so it is not longer found.
const myDiv = document.getElementById("myDIV");
function start() {
setInterval(() => myDiv.classList.toggle("class1"),2000)
}
.class1 {
background-color: coral;
padding: 16px;
opacity: 0;
transition: opacity 1s linear;
}
<div id="myDIV">
<p>I am myDIV.</p>
</div>
<p>Click the button to set a class for myDIV:</p>
<button onclick="start()">Try it</button>
You cannot ask the style.opacity because it is not available to JavaScript if is was not set on the element directly using style
You CAN test the computedStyle but you need to convert the opacity from "0"
to 0
if you want to use ===
- I use the unary plus
const myDiv = document.getElementById("myDIV");
function start() {
myDiv.classList.add("class1")
setTimeout(() => {
const compStyles = window.getComputedStyle(myDiv);
const opacity = compStyles.getPropertyValue('opacity');
console.log(opacity);
if (+opacity === 0) myDiv.classList.remove("class1")
}, 2000);
}
.class1 {
background-color: coral;
padding: 16px;
opacity: 0;
transition: opacity 1s linear;
}
<div id="myDIV">
<p>I am myDIV.</p>
</div>
<p>Click the button to set a class for myDIV:</p>
<button onclick="start()">Try it</button>
Answered By - mplungjan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.