ViDiVe
ViDiVe

Reputation: 134

How to execute a display=none after a fadeout setTimeout?

I'm interested to know if there's a possibility to execute a display='none' after a setTimeout.

The following vanilla JavaScript runs well, but I would like refactoring for a better maintenance.

<div id="id200" style="padding: 7%; text-align: center; background: #87BBBB; color: #FFF;">
Thanks for mailing us
</div>

<div id="id300" style="padding: 20px; background: #000; color: #FFF;">
LOGO
</div>

        <script>
        setTimeout(
            function(){
                document.getElementById("id200").style.opacity = 0;
                document.getElementById("id200").style.transition = "opacity " + 3 + "s";
            }, 3000
        );
        setTimeout(
            function(){
                document.getElementById("id200").style.display='none';
            }, 6000
        );
        </script>

Upvotes: 2

Views: 4138

Answers (1)

Sarah Gro&#223;
Sarah Gro&#223;

Reputation: 10879

You can use the transitionend event instead of a static timer that you'd have to adapt when changing the transition duration:

setTimeout(
  function() {
    var id200 = document.getElementById("id200");
    id200.style.transition = "opacity " + 3 + "s";
    id200.style.opacity = 0;
    id200.addEventListener("transitionend", function() {
      console.log("transition has ended, set display: none;");
      id200.style.display = "none";
    });
  }, 3000
);
<div id="id200" style="padding: 7%; text-align: center; background: #87BBBB; color: #FFF;">
  Thanks for mailing us
</div>

<div id="id300" style="padding: 20px; background: #000; color: #FFF;">
  LOGO
</div>

Upvotes: 9

Related Questions