Abdallah Sakre
Abdallah Sakre

Reputation: 915

Element not becoming hidden on page load in javascript

I'm new to JS. The following JS code is not working when the page loads.

function alert10() {

  var today = new Date().getMinutes();
  if (today > 10) {

    window.onload = function() {
      document.getElementById('timer10').style.display = 'none';
    };

  }
}

I'm calling alert10() as follows :

<header onload="alert10()"> 

The following is the element I'm trying to hide :

<h5 id="timer10"  style=" position:absolute;top: 1px;left: 151px;"></h5>

Upvotes: 1

Views: 103

Answers (2)

Danielozzo
Danielozzo

Reputation: 76

When the header onload function executes, the window onload has probably fired already. If you take the window listener out of the function, the timer is hidden as intended (provided 10 minutes are past since the last hour started). It works as well if you use e.g. a click listener or any other subsequent trigger.

window.onload = function() {
  document.getElementById('timer11').style.display = 'none';
};

function alert10() {
  var today = new Date().getMinutes();
  if (today > 10) {
      document.getElementById('timer10').style.display = 'none';
  } else {
    console.log("10 minutes haven't past since last hour started")
  }
}

I've added a second timer to show both

<header onload="alert10()" onclick="alert10()">
  <h5 id="timer10"  style=" position:absolute;top: 1px;left: 151px;">timer10</h5>
  <h5 id="timer11"  style=" position:absolute;top: 1px;left: 251px;">timer11</h5>
</header>

and a bit of css to make the clickable area apparent

header {
    position: relative;
    width: 100%;
    height: 20vh;
    background-color: mediumseagreen;
}

Upvotes: 1

iLiA
iLiA

Reputation: 3153

Try the following using window.onload:

<html>

<body>
  <h5 id="timer10" style=" position:absolute;top: 1px;left: 151px;">Something</h5>
  <script>
    window.onload = () => {
      var today = new Date().getMinutes();
      if (today > 10) {
        document.getElementById('timer10').style.display = 'none';
      } else {
        alert('minutes is less than 10')
      }
    }
  </script>
</body>

</html>

Upvotes: 4

Related Questions