skip to Main Content

I need to create a link on an HTML page that can only be clicked at a specific time. I have the following code but it doesn’t seem to be working. Preferably the link should be active at a specific time and date. For example, the link could be active at 10:00AM on 10/24/2024 and then inactive either at a specific time or number of hours later.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <style>
    #myButton {
      padding: 10px 20px;
      background-color: gray;
      color: white;
      border: none;
      text-decoration: none;
      display: inline-block;
      pointer-events: none;
      cursor: not-allowed;
    }
    
    #myButton.active {
      background-color: blue;
      cursor: pointer;
      pointer-events: auto;
    }
    
    #myButton.disabled {
      background-color: red;
      cursor: not-allowed;
      pointer-events: none;
    }
  </style>
</head>

<body>

  <h1>Click the link between 10:00 AM and 10:15 AM Eastern Time</h1>

  <a href="#" class="disabled" id="myButton">Link Disabled</a>

  <script>
    const easternTimeOffset = -4;
    const targetStartDate = new Date();
    const targetEndDate = new Date();


    targetStartDate.setUTCHours(10 + easternTimeOffset, 0, 0, 0);
    targetEndDate.setUTCHours(10 + easternTimeOffset, 15, 0, 0);


    const button = document.getElementById("myButton");


    function checkTime() {
      const now = new Date();


      if (now >= targetStartDate && now < targetEndDate) {
        button.href = "https://www.britannica.com/science/world-map";
        button.classList.add("active");
        button.classList.remove("disabled");
        button.textContent = "Click Me Now!";
      } else if (now >= targetEndDate) {
        button.href = "#";
        button.classList.remove("active");
        button.classList.add("disabled");
        button.textContent = "Link Disabled";
      }
    }


    checkTime();
    setInterval(checkTime, 1000);
  </script>



</body>

</html>

2

Answers


  1. // Get the button element  
    const button = document.getElementById("clickMe");  
      
    // Get the current time in EST  
    const now = new Date().toLocaleString("en-US", { timeZone: "America/New_York" });  
    const currentTime = new Date(now);  
      
    // Set the target time to 2:55 PM EST, I used this time because I'm testing now.
    const targetTime = new Date(now);  
    targetTime.setHours(14, 55, 0, 0);  
      
    // If the current time is after 2:55 PM EST and before 3:00 PM EST, remove the "disabled" class  
    if (currentTime > targetTime && currentTime < targetTime.setMinutes(60)) {  
      button.classList.remove("disabled");  
    } else {  
      // Otherwise, add the "disabled" class  
      button.classList.add("disabled");  
    }
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> 
    <!-- Used bootstrap to style -->
    <div class="container">
      <div class="row mt-5">
        <div class="col-3">
          <button type="button" class="btn btn-outline-primary disabled" id="clickMe">Link</button>
        </div>
      </div>
    </div>
    Login or Signup to reply.
  2. In the example below, function linkEvent() renders the HTML to a given element (@param selector) which displays the given start date and time (@param start) and the end time which is determined by the given number of seconds (@param duration). The HTML includes the <a>nchor (aka link) as well. The function updateTime() is then called every second to determine when the link is de/activated.

    The function demo() is included to show it working with a start time of 10 seconds after current time and an end time of 60 seconds. Details are commented in the example.

    // These are pre-determined
    let start, duration, selector, url;
    // These are determined during runtime
    let end, tick;
    
    /**
     * This will render HTML that displays the following info:
     *   - The date at which the link is activated.
     *   - The time at which the link is activated.
     *   - The time at which the link is deactivated.
     * It will also render the link.
     * Next, it will start calling updateTime() every 1000ms (1 sec).
     * @param {Date object} start - The start date.
     * @param {number} duration   - The time in seconds in which 
     *                              the link stays activated.
     * @param {string} selector   - The CSS selector of the element
     * @default "body"              that the HTML will append to.
     */
    function linkEvent(start, duration, selector = "body") {
      // Reference to the element the HTML will be appended to.
      const node = document.querySelector(selector);
      // The time in which the link will be deactivated.
      end = new Date(Date.parse(start) + (duration * 1000));
      // Formatting for the two time values.
      const format = {
        hour: "numeric",
        minute: "2-digit"
      };
      // HTML that will be rendered.
      const html = `
        <p>Click the link on 
          <time>${start.toLocaleDateString()}</time>, 
          starting from <time>${start.toLocaleTimeString([], format)}</time> 
          until <time>${end.toLocaleTimeString([], format)}</time>.</p>
          <a href="#" id="link" class="off"></a>`;
      // Append the HTML to the given element (node).
      node.insertAdjacentHTML("beforeend", html);
      // Start running updateTime() every 1000ms (1 sec).
      tick = setInterval(updateTime, 1000);
    }
    
    /**
     * This will de/activate the link according to the current time.
     */
    function updateTime() {
      // Reference the link.
      const link = document.getElementById("link");
      // Get current time.
      const now = new Date();
      // This is the time remaining before link is activated.
      const untilStart = start - now;;
      // When there is no more time remaining (untilStart), activate link.
      if (untilStart <= 0) {
        link.className = "on";
        link.href = url;
      }
      // If the current time (now) exceeds the ending time (end)...
      if (now > end) {
        // deactivate the link...
        link.className = "off";
        link.href = "#";
        // stop calling updateTime()
        clearInterval(tick);
      }
    }
    
    /**
     * This is an example of how to activate the link at:
     *   - 10/24/2024 = '2024-12-24'
     *   - 6:02 PM = 'T18:02:00.000'
     *   - Eastern = '+4:00'
     * and deactivate the link in:
     *   - 15 minutes = 900 seconds.
    /*
    
    // Time when the link is activated.
    start = new Date('2024-10-24T18:02:00.000+04:00');
    
    // Time in seconds for how long the link is activated.
    duration = 900;
    
    // Link [href] value
    url = "https://example.com";
    
    // Pass start and duration parameters.
    linkEvent(start, duration);
    */
    
    /**
     * This function is to demonstrate linkEvent() starting at:
     * 10 seconds after current time and ending in 60 seconds.
     * The start time may be inaccurate by a few seconds because   
     * is dynamically determined. Normal operation of linkEvent()
     * shouldn't have that problem.
     */
    const demo = () => {
      start = new Date(Date.parse(new Date()) + 10000);
      url = "https://example.com";
      linkEvent(start, 60);
    }
    
    demo();
    #link {
      display: inline-block;
      padding: 10px 20px;
      border: none;
      color: white;
      text-decoration: none;
    }
    
    .on {
      background-color: blue;
      cursor: pointer;
    }
    
    .on::before {
      content: "Click now!";
    }
    
    .off {
      background-color: red;
      cursor: not-allowed;
    }
    
    .off::before {
      content: "Not available";
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search