Why this code is not changing opacity value in progress?
function fadeIn(arg_idElemHtml,arg_opacityValue) {
if(arg_opacityValue < 1){
var objHtml = document.getElementById(arg_idElemHtml);
objHtml.style.display = 'block';
objHtml.style.opacity = arg_opacityValue + 0.1;
arg_opacityValue = parseFloat(arg_opacityValue) + 0.1;
setTimeout(fadeIn(arg_idElemHtml,arg_opacityValue), 400);
}
}
#msg {background-color:red;display:none;opacity:0.0}
<button id="bt" onclick="fadeIn('msg',0);">GO</button>
<div id="msg">content message</div>
Here is an example to illustrate my comment regarding using CSS to handle the fade in on click.
I've used
addEventListener()
instead of inline handler assignment which is generally recommended. I have also used classes to define the re-usable fade related CSS. This avoids duplication if you are going to reuse the functionality as well as resolving specificity issues that arise in mixingid
andclass
based style assignments.For extended discussion see:
Transitions on the CSS display property.
Take the time to read through all the answers, the top voted or accepted answer may not be the most relevant to your situation.
Edit - Fade Out
It is a little more involved to add a fade out effect, since you don't want to set
display: none;
until the animation is complete. Here is an example using the animationend event to cleanup/complete the transition.Whether showing or hiding the element we first add a listener on the
animationend
event that will cleanup the classes added to handle the animation. When adding the listener it is important to pass an options object with{once: true}
which will remove the listener after the first time it runs. This is to ensure we don't create multiple listeners on the same element.Having added the cleanup listener we proceed to add the relevant fade class — If the element is hidden we add the
fade-in
class and remove thehidden
class, otherwise we add thefade-out
class to begin the animation. You'll note that we are reusing the same keyframes CSS by using the animation-direction property to reverse it in thefade-out
class.