Javascript hide and display id

Viewed 23

I don't want a button I want a timer instead that counts down 5 seconds then the javascript function executes on page load

<!DOCTYPE html>
<head>
    <link rel="stylesheet" href="css/app.min.css" />
    <title>
        Test
    </title>
</head>
<body>
    <!-- I don't want a button I want a timer instead that counts down 5 seconds then the javascript function executes -->

    <button onclick="myFunction()">Click Me</button>

    <div id="myDIV", class="myDIV">
        Initializing Hide
      </div>

      <div id="myDIVS", class="myDIVS">
        Hide Successful
      </div>


    <script type="text/javascript">
        function myFunction(){
            var target = document.getElementById("myDIV");
            var show = document.getElementById("myDIVS");
            if(target.style.display = "none"){
                // target.style.display = "block";
                show.style.display = "block";
            }else{
                show.style.display = "block";
            }
        }

        
    </script>
</body>

<style>
    .myDIV{
        background-color: aqua;
        margin: 30px;
        padding: 50px 30px;
        /* display: none; */
    }

    .myDIVS{
        background-color: green;
        margin: 30px;
        padding: 50px 30px;
        display: none;
    }
</style>```
1 Answers

You need to use setTimeout(). Just put the onClick code inside this, also I have corrected the = vs. == mistake.

function myFunction() {
  var target = document.getElementById("myDIV");
  var show = document.getElementById("myDIVS");
  if (target.style.display == "none") {
    target.style.display = "block";
    show.style.display = "none";
  } else {
    target.style.display = "none";
    show.style.display = "block";
  }
}

setTimeout(myFunction, 5000);
.myDIV {
  background-color: aqua;
  margin: 30px;
  padding: 50px 30px;
  /* display: none; */
}

.myDIVS {
  background-color: green;
  margin: 30px;
  padding: 50px 30px;
  display: none;
}
<div id="myDIV" class="myDIV">
  Initializing Hide
</div>

<div id="myDIVS" class="myDIVS">
  Hide Successful
</div>

Wait for five seconds and see?

Related