2

My problem is that only fadeOut works but not fadeIn. I don't use CSS or jQuery for it. And how can I make my code more effective.

The code:

HTML:

<div class="circle"id="circle1"onclick="myFunction()"></div>
<div class="circle"id="circle2" style="visibility:visible" ></div

JavaScript:

function myFunction() {
  var element = document.getElementById("circle2");
  if (element.style.visibility === "visible") {
    var op = 1;
    var timer = setInterval(frame, 100)

    function frame() {
      if (op <= 0.1) {
        clearInterval(timer);
        element.style.visibility = "hidden";
      }
      element.style.opacity = op;
      op -= op * 0.1;
    }
  } else {
    var op = 0;
    var timer = setInterval(frame, 10)

    function frame() {
      if (op >= 0.95) {
        clearInterval(timer);
        element.style.visibility = "visible";
      }
      element.style.opacity = op;
      op += op * 0.1;
    }
  }
}

1 Answer 1

1

There are a few reasons this is not working.

  1. 0 * anything is still 0 so var op=0; and op += op * 0.1 will always be zero.

  2. It is set to hidden not visible while transitioning to fully visible.

I played around with it to make it work but I refactored you code to fit my style while I did it. This is what I came up with.

function myFunction() {

    var element = document.getElementById( "circle2" );
    var op;
    var timer;

    if ( element.style.visibility === "visible" ) {
        op = 1;
        timer = setInterval( fadeOut, 100 )
    } else {
        op = 0.1;
        timer = setInterval( fadeIn, 100 )
    }

    function fadeOut() {
        if ( op <= 0.1 ) {
            clearInterval( timer );
            element.style.visibility = "hidden";
        }
        element.style.opacity = op;
        op -= op * 0.1;
    }

    function fadeIn() {
        element.style.visibility = "visible";
        if ( op >= 0.95 ) {
            clearInterval( timer );
        }
        element.style.opacity = op;
        op += op * 0.1;
    }
}
<div class="circle"id="circle1"onclick="myFunction()">hello</div>
<div class="circle"id="circle2" style="visibility:visible" >Test</div>

Sign up to request clarification or add additional context in comments.

2 Comments

why ist the element.style.visibility = "visible"; outside of the if statement? It works but why.
Because of issue number 2. We need the element to have the visible attribute so when we change the opacity we will see the change. If it is in the if statement the opacity will change been we won't see anything because the element when still be hidden.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.