Reputation:
I'm trying to make element dissapear at the end of animation but it doesn't work, can someone explain how to make exit animation with element dissappearing at the end of it?:
var test = document.getElementById("test");
test.addEventListener("click", displayOpacity);
function displayOpacity(event){
event.target.style.animation = "changeOpacity 1s linear";
if(event.target.style.opacity === 0){
event.target.style.display = "none";
}
}
.container .test {
text-align: center;
padding: 100px;
color: #fff;
background-color: #00f;
max-width: 500px;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
}
@-webkit-keyframes changeOpacity {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes changeOpacity {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
<body>
<div class="container">
<div class="test" id="test">Custom Text</div>
</div>
<script src="main.js"></script>
</body>
Upvotes: 3
Views: 549
Reputation: 337580
Your issue is because the animation-fill-mode
is not being respected as you're overwriting it by setting the animation
rule directly on the element itself.
To fix this change your JS code to add a class on the element, and put the animation
rule in there, along with the required fill mode:
var test = document.getElementById("test");
test.addEventListener("click", displayOpacity);
function displayOpacity(event) {
this.classList.add('changeOpacity');
}
.container .test {
text-align: center;
padding: 100px;
color: #fff;
background-color: #00f;
max-width: 500px;
}
.changeOpacity {
animation: changeOpacity 1s linear forwards;
}
@-webkit-keyframes changeOpacity {
0% { opacity: 1; }
100% { opacity: 0; }
}
@-webkit-keyframes changeOpacity {
0% { opacity: 1; }
100% { opacity: 0; }
}
@keyframes changeOpacity {
0% { opacity: 1; }
100% { opacity: 0; }
}
<div class="container">
<div id="test" class="test">
Test
</div>
</div>
Upvotes: 1
Reputation: 42
The animation time is 1 second
event.target.style.animation = "changeOpacity 1s linear";
so just make a timeout
setTimeout(function(){
event.target.style.display = "none";
},1000)
Upvotes: 1
Reputation: 41893
Since you have tagged jQuery
, wouldn't be it easier to do it with .fadeOut()
? The display
attribute of the element is being set to none
just after the animation has ended.
$('#test').click(function(){
$(this).fadeOut();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='test'>Text</div>
Upvotes: 2