skip to Main Content

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>

2

Answers


  1. That is because you set the callback in setTimeout wrong.

    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;
          
          // Like this
          setTimeout(() => fadeIn(arg_idElemHtml,arg_opacityValue),400);
          
          // Or
          // setTimeout(fadeIn.bind(this, 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>
    Login or Signup to reply.
  2. 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 mixing id and class based style assignments.

    const bt = document.getElementById('bt');
    
    bt.addEventListener('click', () => fadeIn('msg'));
    
    function fadeIn(id) {
      const objHTML = document.getElementById(id);
      objHTML.classList.toggle('hidden');
    }
    #msg {
      background-color: red;
    }
    
    .fade-in {
      display: block;
      animation: fadeInAnimation 2s;
    }
    
    .hidden {
      display: none;
    }
    
    @keyframes fadeInAnimation {
      from {
        opacity: 0;
      }
      to {
        opacity: 1;
      }
    }
    <button id="bt">Go</button>
    <div id="msg" class="fade-in hidden">content message</div>

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search