Reputation: 608
CSS
can't make a transition from display: none
to display: block
for that i'm trying to make it using javascript i don't want to use visibility: hidden
and height: 0
or transform: scale(0)
for that i'm using javascript to make a transition from display: none
to display: block
The code below work when i add the active
class the transition working fine, But when i remove the class active
the transition it's not working
How can i make the transition work in both when i add and when i remove the class active using javascript and css ?
let parents = document.querySelectorAll('.parent');
parents.forEach(p => {
p.addEventListener("click",() => {
if(p.classList.contains('active')){
setTimeout(function () {
p.nextElementSibling.classList.remove("visually");
}, 20);
p.classList.remove("active");
}else{
p.classList.add("active");
setTimeout(function () {
p.nextElementSibling.classList.add('visually');
}, 20);
}
});
});
.link-inner {
cursor: pointer;
}
.toggle {
opacity: 0;
display: none;
transition: all .5s ease-in-out;
}
.parent.active+.toggle {
display: block;
}
.parent.active+.visually {
opacity: 1;
}
<div class="link">
<div class="link-inner parent">
<div class="linkText">
<h4>Title</h4>
</div>
</div>
<div class="linkInfo toggle ">
<a href="#" target="_blank">link 1</a>
</div>
</div>
<div class="link">
<div class="link-inner parent">
<div class="linkText">
<h4>Title</h4>
</div>
</div>
<div class="linkInfo toggle ">
<a href="#" target="_blank">link 2</a>
</div>
</div>
Upvotes: 0
Views: 363
Reputation: 1188
You were actually really nearly there. You just had to swap the calls when removing classes and add a bit more of a delay in your setTimeout
let parents = document.querySelectorAll('.parent');
parents.forEach(p => {
p.addEventListener("click",() => {
if(p.classList.contains('active')){
// remove the class that sets opacity so it fades away
p.nextElementSibling.classList.remove("visually");
setTimeout(function () {
// remove the class that sets display: block after the opacity is gone
p.classList.remove("active");
}, 500);
} else {
p.classList.add("active");
setTimeout(
function () {
p.nextElementSibling.classList.add('visually');
},
20
);
}
});
});
Upvotes: 1