Here I have a function that fades a square box with id=\"box\"
as soon as the page loads. I tried but failed to find out how to fade in the box again or simply
My solution is not really pure Js as it involves CSS animation like that of @Anarion but I included Js codes that is needed to do this on events like onclick
. Check it out:
function showHelloWorld(){
var helloWorldElement = document.getElementById('hello-world');
helloWorldElement.classList.remove('hide','fade-out');
helloWorldElement.classList.add('fade-in')
}
function hideHelloWorld(){
var helloWorldElement = document.getElementById('hello-world');
helloWorldElement.classList.add('fade-out');
helloWorldElement.classList.remove('fade-in');
setTimeout(function(){
helloWorldElement.classList.add('hide');
},2000) //Note that this interval matches the timing of CSS animation
}
body{
text-align:center;
}
#hello-world{
font-size:36px;
}
.hide{
display:none;
}
.fade-in{
animation: 2s fadeIn;
}
.fade-out{
animation: 2s fadeOut;
}
@keyframes fadeIn{
from{
opacity:0;
}
to{
opacity:1;
}
}
@keyframes fadeOut{
from{
opacity:1;
}
to{
opacity:0;
}
}
Hello World