How will I add fadeout animation in this javascript code?
document.getElementById("mt-alerts").style.display="block";
setTimeout(function(){
document.getElementById("mt-alerts").style.display="none";
}, 2000);
Instead of using display, you need to start with opacity for this.
The idea is simply decrease the opacity of your element until it reaches the 0, then set its display as none. To fade in you can repeat the idea in reverse.
function js_fadeOut(targetID, intervalMs, fadeWeight) {
var fadeTarget = document.getElementById(targetID);
var fadeEffect = setInterval(function () {
if (!fadeTarget.style.opacity) {
fadeTarget.style.opacity = 1;
}
if (fadeTarget.style.opacity > 0) {
fadeTarget.style.opacity -= fadeWeight;
} else {
fadeTarget.style.display = "none";
clearInterval(fadeEffect);
}
}, intervalMs*fadeWeight);
}
<div id='target' style='padding:8px; background:lightblue;' onclick='js_fadeOut("target", 200, 0.1)'>Click to fadeOut</div>