How to make a visual timer for one hour after the specified time in data-time-created in JQuery

You can use jQuery to create a visual timer based on the time specified in the data-time-created attribute. Here is an example implementation:

HTML Code:

<div class="order-counter" data-time-created="2024-12-11T03:21:21.893Z"></div>

jQuery Code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
    // Get the element with the data-time-created attribute
    const $counter = $('.order-counter');
    
    // Get the time from the data-time-created attribute
    const createdTime = $counter.data('time-created');
    
    // Parse the time and add 1 hour
    const endTime = new Date(new Date(createdTime).getTime() + 60 * 60 * 1000);
    
    // Update the timer every second
    const timerInterval = setInterval(() => {
        const currentTime = new Date();
        const timeLeft = endTime - currentTime;

        // If time is up
        if (timeLeft <= 0) {
            clearInterval(timerInterval);
            $counter.text('Time is up!');
            return;
        }

        // Calculate remaining time
        const hours = Math.floor((timeLeft / (1000 * 60 * 60)) % 24);
        const minutes = Math.floor((timeLeft / (1000 * 60)) % 60);
        const seconds = Math.floor((timeLeft / 1000) % 60);

        // Format the remaining time and display it
        const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        $counter.text(`Time left: ${timeString}`);
    }, 1000);
});
</script>

What the script does:

  1. Reads the creation time from the data-time-created attribute.
  2. Adds 1 hour to the provided time.
  3. Every second, it calculates the remaining time and updates the text inside the .order-counter element.
  4. When the time is up, the timer stops, and it displays the message Time is up!.

Result:

The <div class="order-counter"> element will show a countdown in the format HH:MM:SS. After the time is up, it will display a message saying that the time is up.

If there may be multiple elements with the .order-counter class on a page, you need to handle each element individually. Here’s how you can rewrite the code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
    // For each element with the class .order-counter
    $('.order-counter').each(function () {
        const $counter = $(this); // Current element
        const createdTime = $counter.data('time-created'); // Time from data-time-created
        const endTime = new Date(new Date(createdTime).getTime() + 60 * 60 * 1000); // End time

        // Update the timer every second for the current element
        const timerInterval = setInterval(() => {
            const currentTime = new Date();
            const timeLeft = endTime - currentTime;

            // If time is up
            if (timeLeft <= 0) {
                clearInterval(timerInterval);
                $counter.text('Time is up!');
                return;
            }

            // Calculate remaining time
            const hours = Math.floor((timeLeft / (1000 * 60 * 60)) % 24);
            const minutes = Math.floor((timeLeft / (1000 * 60)) % 60);
            const seconds = Math.floor((timeLeft / 1000) % 60);

            // Format the remaining time and update the text
            const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            $counter.text(`Time left: ${timeString}`);
        }, 1000);
    });
});
</script>

What Changed:

  1. The .each() method is used to loop through all elements with the .order-counter class.
  2. A separate timer (setInterval) and calculations are created for each element individually.
  3. All variables related to the timer are scoped to the current element using $(this).

Result:

Each .order-counter element on the page will have its own countdown. When the time is up for a specific timer, it will show the message Time is up!.

This approach scales to any number of timers on the page.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

Why Files with Identical Content (*.js, *.php, *.css) Can Have Different Sizes?

When developers compare files with identical content but notice that their sizes differ, it can be perplexing. Let’s explore why this happens and what factors influence the size of files with extensions like *.js, *.php, and *.css. 1. File Encoding One of the key factors affecting file size is text encoding. The most common encodings…
Read more

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more