Pressing the button will navigate to page X initially, and then after the countdown finishes, it will

A unique surprise is in store for my wife with this special website. The home page features a countdown to a significant date, and only one button unlocks the gift. I am looking for a way to either keep the button locked until the countdown ends or have it lead to a teasing page saying "oh no you don't" before revealing the actual prize when the timer hits zero. It might sound confusing πŸ˜… but any help on making this happen would be greatly appreciated.

For easier debugging and previewing, here is the link to my CodePen: https://codepen.io/Probler/pen/KKLJxqO

const targetDate = new Date('July 15, 2024 00:00:00');
function updateCountdown() {
    const now = new Date();
    const remainingTime = targetDate - now;

    if (remainingTime <= 0) {
        // If the countdown is finished, display all zeros
        document.getElementById('days').textContent = '00';
        document.getElementById('hours').textContent = '00';
        document.getElementById('minutes').textContent = '00';
        document.getElementById('seconds').textContent = '00';
        clearInterval(interval); // Stop the countdown
        return;
    }

    // Calculate the time parts
    const days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
    const hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

    // Display the time parts in the corresponding span elements
    document.getElementById('days').textContent = days.toString().padStart(2, '0');
    document.getElementById('hours').textContent = hours.toString().padStart(2, '0');
    document.getElementById('minutes').textContent = minutes.toString().padStart(2, '0');
    document.getElementById('seconds').textContent = seconds.toString().padStart(2, '0');
}

// Update the countdown every second
const interval = setInterval(updateCountdown, 1000);

// Initial call to display the countdown immediately
updateCountdown();

Answer β„–1

After understanding your requirements, here is the solution:

Start by creating two separate HTML pages - one for the surprise and another for the disappointment.

Next, update the button code as follows:

<button class="trigger" onclick="unlockSurprise()">Trigger</button>

Then, implement the JavaScript function:

function unlockSurprise() {
    if (endDate <= new Date()) {
        window.location.href = 'surprise.html';
    } else {
        window.location.href = 'disappointment.html';
    }
}

Complete code snippet:

const endDate = new Date('September 30, 2023 23:59:59');
function unlockSurprise() {
    if (endDate <= new Date()) {
        alert("Surprise unlocked! Enjoy!");
        window.location.href = 'surprise.html';
    } else {
        alert("Oops, not yet time for the surprise.");
        window.location.href = 'disappointment.html';
    }
}
Note: Make sure to adjust the date and page URLs according to your specific needs.

Answer β„–2

In order to add a functional onClick directly when the timer reaches zero, I made some DOM manipulation adjustments.

<span style="color: #ffd700;">
    <button class="download" id="download">Open</button>
  </span>

became

<span style="color: #ffd700;">
    <button class="download" onclick="window.location.href='special.html'">Open</button>
  </span>

and

const remainingTime = targetDate - now;
let button = document.getElementById("download");

if (remainingTime <= 0) {
    // If the countdown is finished, display all zeros
    document.getElementById('days').textContent = '00';
    document.getElementById('hours').textContent = '00';
    document.getElementById('minutes').textContent = '00';
    document.getElementById('seconds').textContent = '00';
    clearInterval(interval); // Stop the countdown
    button.onclick = function() {
      window.location.href = 'https://www.google.com.br';
    };
    return;
}

became

const remainingTime = targetDate - now;

if (remainingTime <= 0) {
    // If the countdown is finished, display all zeros
    document.getElementById('days').textContent = '00';
    document.getElementById('hours').textContent = '00';
    document.getElementById('minutes').textContent = '00';
    document.getElementById('seconds').textContent = '00';
    clearInterval(interval); // Stop the countdown
    return;
}

Answer β„–3

Implement a hidden button that navigates to a new page and once the countdown ends, switch the visibility of buttons. For instance, clicking on the Open button will direct you to https://example.com. Additionally, there is a demonstration button called T-minus Zero which signifies the end of the countdown. Clicking this button simulates the end of the countdown. When the countdown reaches zero, the text color of the Open button should turn yellow. Clicking it at this point should navigate to the new target page which is .

Detailed instructions are provided within the code snippet below.

let targetDate = new Date('July 15, 2024 00:00:00');

function updateCountdown() {
  const now = new Date();
  const remainingTime = targetDate - now;

  if (remainingTime <= 0) {
    // If the countdown is finished, display all zeros
    document.getElementById('days').textContent = '00';
    document.getElementById('hours').textContent = '00';
    document.getElementById('minutes').textContent = '00';
    document.getElementById('seconds').textContent = '00';
    clearInterval(interval); // Stop the countdown

    // Hide the first button and reveal the second button
    document.getElementById('close').classList.add("hidden");
    document.getElementById('open').classList.remove("hidden");
    return;
  }

  // Calculate the time parts
  const days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
  const hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

  // Display the time parts in the corresponding span elements
  document.getElementById('days').textContent = days.toString().padStart(2, '0');
  document.getElementById('hours').textContent = hours.toString().padStart(2, '0');
  document.getElementById('minutes').textContent = minutes.toString().padStart(2, '0');
  document.getElementById('seconds').textContent = seconds.toString().padStart(2, '0');
}

// Update the countdown every second
const interval = setInterval(updateCountdown, 1000);

// Initial call to display the countdown immediately
updateCountdown();

// For demonstration purposes only
document.getElementById('zero').onclick = function() {
  targetDate = new Date();
};
/* βΈΈ A change for aesthetics */
... (CSS styles omitted for brevity)
<body>
  <!--Center Content-->
  ... (HTML structure omitted for brevity)
</body>

Answer β„–4

Although there were helpful answers provided here, I managed to discover a more effective implementation that suited my needs.

I incorporated an event listener into my JavaScript code:

function handleButton() {
    if (remainingTime > 0) {
        // Redirect to fake loading page
        window.location.href = '/Images/fakeloading.html';
    } else {
        // Redirect to special prize page
        window.location.href = '/Images/special.html';
    }
}

// Attach event listener to the button once the DOM content is fully loaded
document.addEventListener('DOMContentLoaded', () => {
    const downloadbtn = document.getElementById('downloadbtn');
    downloadbtn.addEventListener('click', handleButton);
});

Here's what I implemented on the HTML side:

<span><button id="downloadbtn" class="open">Open</button></span>

This event listener checks the timer and redirects to the fake webpage if it's above 0, otherwise it goes to the real one when it hits 0.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fetch information from MySQL, create a new row for each data entry

Currently, I am working on a project for my school that involves retrieving student works from a database. For the homepage of my project, I have set up 10 divs to hold the data returned from a query. The reason I preset these divs is because I only need ...

Uploading a file to a server using HTML and PHP: a step-by-step guide

Looking to utilize PHP as a proxy for uploading files to a server. Any advice on how I can send the uploaded files along with a Basic Authorization header? ...

Finding the value of a radio button dynamically created by jQuery

I am having an issue retrieving the value of a radio button that is generated using jQuery. I suspect there may be some problems with event handling. Below is my code: HTML <div id="divOption1"></div> The jQuery script to generate t ...

Vue.js Ajax call is throwing a bizarre error: TypeError - str.replace function not recognized

Recently, I encountered a puzzling error message: vue-resource.common.js Uncaught TypeError: str.replace is not a function while working on an ajax call to retrieve some data: export default { data: () => ({ recipes: [] }), ready() { ...

What is the purpose of using translateY(-50%) to vertically center an element that is positioned at top: 50%?

I've noticed that this code successfully aligns a div vertically within its parent element: .element { position: relative; top: 50%; transform: translateY(-50%); } My curiosity lies in the reasoning behind this. Initially, I thought that the p ...

The overflowing issue with the Nextjs Tailwind Marquee Component is causing a display

I've recently developed a unique nextjs/tailwind component. This component displays an isometric marquee that scrolls horizontally. However, I'm facing an issue where the content overflows to the right and causes the page to become horizontally s ...

Trouble with Showing Bootstrap 5 Icon

My current project involves creating a website using Bootstrap 5 icons, but I'm encountering an issue where the icon is not displaying correctly. The expected appearance should be like this [![Example1][1]][1], but it actually looks like this [![Examp ...

The form within the while loop is only functioning with the initial result

Within a while loop, I have a form that is being processed with ajax. The issue is that it only works on the first form and not on the others. Can someone take a look? <?php while($a = $stmt->fetch()){ ?> <form method="post" action=""> ...

When utilizing Express and passport, an error occurs stating that req.isAuthenticated is undefined

After successfully setting up a backend express server in the past few hours, I decided to implement authorization by following a tutorial. The login functionality works perfectly, but when attempting to access /authrequired (a restricted page that require ...

Is there a secure alternative in Typescript for handling null values, such as a "safe operator"?

I'm currently working on implementing a feature in my Angular application where I need to toggle the visibility of a div using ngIf. Below you can find the snippet of HTML code I am using: <div *ngIf="damageReportToPolice()"> </div> Her ...

SyntaxError: An invalid character was encountered (at file env.js, line 1, column 1)

This marks my debut question so kindly indulge me for a moment. I recently stumbled upon a guide that outlines how to dynamically alter environment variables in a React project without the need for re-building. You can find the guide here. The method work ...

Error: The default export is not a component compatible with React in the specified page: "/"

I'm facing an issue while building my next app. Despite using export default, I keep encountering an error that others have mentioned as well. My aim is to create a wrapper for my pages in order to incorporate elements like navigation and footer. vi ...

Repeated information in HTML tables

I am currently working with two HTML tables and two sets of JSON data. Initially, I load one table with the tableData which has a default quantity of 0. In my HTML form, there are three buttons - save, load draft, and edit. Upon clicking on load draft, I p ...

Struggling to add an object to my Topic array using push

I'm in the process of developing a forum platform. Below is my Topic schema: const topicSchema = new mongoose.Schema({ author: { type: String, ref: "User", // Reference to the user who created the Topic required: true, }, t ...

CriOS unable to recognize OPTIONS request from Tomcat 8

My application uses POST requests with CORS for backend services (from www.mydomain.com to api.mydomain.com). The backend is served by a Tomact8 server, implementing a CORSResponseFilter as shown below: public class CORSResponseFilter implements Container ...

Creating a Javascript object from a JSON string

Looking for a way to convert a JSON string into a JavaScript object? You can make use of the following code snippet obtained from the server: JSON String: ["{"title":"Admin Dhaka","href":"#0","dataAttrs":[],"data":["{\"title\":\"BNS HAJI M ...

Why isn't Gzip compression working in webpack? What am I missing?

After comparing the compression results of manual webpack configuration and create-react-app for the same application, it became clear that create-react-app utilizes gzip compression, resulting in a significantly smaller final bundle size compared to manua ...

Using Highcharts within a Vue.js component

I'm having trouble creating graphical components with Highcharts and Vue.js because I can't figure out how to dynamically set the id attribute that Highcharts needs to render properly. Does anyone know how to set the id dynamically? This is the ...

Strategies for effectively managing numerous API requests

My current setup involves fetching about five API calls simultaneously. While it works at times, most of the time it results in a fetch error. Is there a way to prevent these errors from occurring when running the API calls? app.post("/movie/:movieN ...

Using the Ruby on Rails redirect_to method

Imagine I have the following line in my controller: redirect_to "/sessions/attempt", provider: 5 Now, this is what my attempt.html.erb looks like: <h1>attempt</h1> <%= provider %> It's clear that this setup isn't functioning ...