Can I time content visibility in HTML based on time of day?

ROLDXR :

I have this local site where I want to show specific parts (divs) on a specific time of day. Is this possible? if so, how can I implement this? thanks.

I have this simple example page:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>timed content</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body> 

<div class="container">
   <h2>timed content</h2>
   <div id="eight" class="well">only show 8AM</div>
  
   <div id="eleven" class="well">only show at 11AM</div>
  
   <div id="three" class="well">only show at 3PM</div>
</div>
</body>
</html>

DaCurse :

You can achieve that with JS by using the Date object, and providing some data on each element about what hour you'd wish to show it at.

let now = new Date(); // Get the current time
let elem = document.querySelector(`div[data-hour="${now.getHours()}"]`); // Select the element that's supposed to be shown for the current time

if (elem) { // If its exists, show it
  elem.style.display = 'block';
}
div[data-hour] {
  /* By default hide all elements that are "timed" */
  display: none;
}
<div class="container">
  <h2>timed content</h2>
  <div data-hour="0">0:00</div>
  <div data-hour="1">1:00</div>
  <div data-hour="2">2:00</div>
  <div data-hour="3">3:00</div>
  <div data-hour="4">4:00</div>
  <div data-hour="5">5:00</div>
  <div data-hour="6">6:00</div>
  <div data-hour="7">7:00</div>
  <div data-hour="8">8:00</div>
  <div data-hour="9">9:00</div>
  <div data-hour="10">10:00</div>
  <div data-hour="11">11:00</div>
  <div data-hour="12">12:00</div>
  <div data-hour="13">13:00</div>
  <div data-hour="14">14:00</div>
  <div data-hour="15">15:00</div>
  <div data-hour="16">16:00</div>
  <div data-hour="17">17:00</div>
  <div data-hour="18">18:00</div>
  <div data-hour="19">19:00</div>
  <div data-hour="20">20:00</div>
  <div data-hour="21">21:00</div>
  <div data-hour="22">22:00</div>
  <div data-hour="23">23:00</div>
</div>

If you want to check for more than just the current hour, you'd need to provide more data on each element and check for it. If you want multiple elements to show at a certain time, use document.querySelectorAll and iterate over the results.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=9709&siteId=1