Peppa-pig
Peppa-pig
KPCKevin Powell - Community
Created by Peppa-pig on 2/6/2025 in #front-end
Failing to animate(using transition) something from display none to block on hover
So this is some very simple code I have to replicate the problem I am having in my main project:
import "./Test.scss"

const Test = () => {

function addClass(){
const el=document.querySelector(".test")
if(el){
el.classList.add("active")
}
}
function removeClass(){
const el=document.querySelector(".test")
if(el){
el.classList.remove("active")
}
}
return (
<div className='my-container'>
<button className='btn btn-primary btn-lg' onClick={addClass}></button>
<button className='btn btn-danger btn-lg' onClick={removeClass}></button>
<div className='test'>Test</div>
</div>
)
}

export default Test

.test{

margin: 200px;
background-color: red;
display:none;
width:300px;
height:300px;
transition: all 3s linear;
transition-behavior: allow-discrete;
&:hover{
opacity: 1;
display: block;
}
&.active{

display: block;
}
}
@starting-style {
.test {
opacity: 0;
}
}

.my-container{
height:600px;
width:100dvw
}

import "./Test.scss"

const Test = () => {

function addClass(){
const el=document.querySelector(".test")
if(el){
el.classList.add("active")
}
}
function removeClass(){
const el=document.querySelector(".test")
if(el){
el.classList.remove("active")
}
}
return (
<div className='my-container'>
<button className='btn btn-primary btn-lg' onClick={addClass}></button>
<button className='btn btn-danger btn-lg' onClick={removeClass}></button>
<div className='test'>Test</div>
</div>
)
}

export default Test

.test{

margin: 200px;
background-color: red;
display:none;
width:300px;
height:300px;
transition: all 3s linear;
transition-behavior: allow-discrete;
&:hover{
opacity: 1;
display: block;
}
&.active{

display: block;
}
}
@starting-style {
.test {
opacity: 0;
}
}

.my-container{
height:600px;
width:100dvw
}

So I then import it in my main component. The problem occurs here is that this animates when I click the button to add it, but disappears without animating. When I add opacity: 0; to "test" and opacity:1 to "active", the opposite occurs. But none that animates both ways. I am aware that there are easier solutions(with keyframes, or using visibility), but I want to know why this doesnt work.
22 replies