I wrote the script code.
I want to have a fade effect on the script.
How can I add a fade effect to this code?
please help..!
※I used a translator because I couldn’t speak English. That is why my words may not be natural. Please understand.
const toggleBtn = document.querySelector('.btn');
const activeOn = document.querySelector('#wrap');
toggleBtn.addEventListener('click', () => {
activeOn.classList.toggle('active');
});
a {
color: black;
text-decoration: none;
}
.btn {
display: inline-block;
font-size: 20px;
font-weight: 600;
}
#wrap {
position: relative;
display: none;
}
#wrap.active {
display: block;
}
.contents {
position: relative;
display: inline-block;
margin: 15px;
padding: 30px;
border: 1px solid #555;
}
<a class="btn" href="#none">Click</a>
<div id="wrap">
<div class="contents">
Active Contents!
</div>
</div>
2
Answers
The best way to do the fade effect is using CSS transition.
One thing to note is CSS transitions don’t work if you’re toggling
display: block
anddisplay: none
, so you need to instead consider usingvisibility
oropacity
attributes.Here’s the working code:
You can achieve this with
opacity
instead ofdisplay
, like this: