Disable the countdown timer and hide the hours, minutes, and seconds once it reaches the

I am just starting to learn javascript and I'm struggling with removing the expired part of my countdown. When the countdown reaches 0 for days, hours, minutes, etc., I want it to display "Expired" instead.

Below is the JavaScript code:


var items = document.querySelectorAll('#clock');
for (var i = 0, len = items.length; i < len; i++) {
    (function () {
        var e = new Date("2018-12-31").getTime(),
            t = this.querySelector("[data-js=countdown]"),
            n = this.querySelector("[data-js=countdown-endtext]"),
            day = this.querySelector("[data-js=countdown-day]"),
            hour = this.querySelector("[data-js=countdown-hour]"),
            min = this.querySelector("[data-js=countdown-minute]"),
            sec = this.querySelector("[data-js=countdown-second]"),
            s = this.gjs_countdown_interval;
        s && s && clearInterval(s);
        var l = function (e, t, n, s) {
                day.innerHTML = e < 10 ? "0" + e : e,
                    hour.innerHTML = t < 10 ? "0" + t : t,
                    min.innerHTML = n < 10 ? "0" + n : n,
                    sec.innerHTML = s < 10 ? "0" + s : s
            },
            u = function () {
                var day = (new Date).getTime(),
                    hour = e - day,
                    min = Math.floor(hour / 864e5),
                    sec = Math.floor(hour % 864e5 / 36e5),
                    s = Math.floor(hour % 36e4 / 6e4),
                    u = Math.floor(hour % 6e4 / 1e3);
                l(min, sec, s, u), hour < 0 && (clearInterval(c),
                    n.innerHTML = "EXPIRED",
                    t.style.display = "none",
                    n.style.display = "")
            };
        if (e) {
            var c = setInterval(u, 1e3);
            this.gjs_countdown_interval = c,
                n.style.display = "none",
                t.style.display = "", u()
        } else l(0, 0, 0, 0)
    }.bind(items[i]))();
}

HTML:

<section class="flex-sect">
    <div id="clock" class="countdown">
        <span data-js="countdown" class="countdown-cont">
        <div class="countdown-block">
            <div data-js="countdown-day" class="countdown-digit"></div>
            <div class="countdown-label">days</div>
        </div>
        <div class="countdown-block">
            <div data-js="countdown-hour" class="countdown-digit"></div>
            <div class="countdown-label">hours</div>
        </div>
        <div class="countdown-block">
            <div data-js="countdown-minute" class="countdown-digit"></div>
            <div class="countdown-label">minutes</div>
        </div>
        <div class="countdown-block">
            <div data-js="countdown-second" class="countdown-digit"></div>
            <div class="countdown-label">seconds</div>
        </div>
        </span>
        <span data-js="countdown-endtext" class="countdown-endtext"></span>
    </div>
</section>

Thank you for your assistance!

Answer №1

To determine if a time period equals zero and all the larger time periods are also zero, you can follow these steps:

if (day == 0) {
    day.innerHTML = "";
}
if (day == 0 && hour == 0) {
    hour.innerHTML = "";
}
if (day == 0 && hour == 0 && min == 0) {
    min.innerHTML = "";
}
if (day == 0 && hour == 0 && min == 0 && sec == 0) {
    sec.innerHTML = "";
    n.innerHTML = "Expired";
}

Answer №2

It was a great feeling to finally resolve my errors by making a simple adjustment: rather than using {{ request.GET.date }} GMT-7 as the input, provide your own parameters and watch it work like a charm!

<script>
    var deadline = new Date("{{ request.GET.date }} GMT-7").getTime();

    var x = setInterval(function () {

        var now = new Date().getTime();
        var t = deadline - now;
        var days = Math.floor(t / (1000 * 60 * 60 * 24));
        var hours = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((t % (1000 * 60)) / 1000);

        if (days == 0) {
            document.getElementById("day").innerHTML = '';
            document.getElementById("day-title").innerHTML = '';
        } else if (days ==1) {
            document.getElementById("day-title").innerHTML = 'Day';
            document.getElementById("day").innerHTML = days;
        } else {
            document.getElementById("day").innerHTML = days;
            document.getElementById("day-title").innerHTML = 'Days';
        }
        if (hours != 0) {
            document.getElementById("hour").innerHTML = hours;
        } else {
            document.getElementById("hour").innerHTML = '';
            document.getElementById("hour-title").innerHTML = '';
        }

        document.getElementById("minute").innerHTML = minutes;
        document.getElementById("second").innerHTML = seconds;
        if (t < 0) {
            clearInterval(x);
            document.getElementById("clock").innerHTML = '';
        }
    }, 1000);
</script>

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

Storing a JavaScript file using C# code snippets

<head runat="server"> <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title> <link href="../../Content/css/layout.css" rel="stylesheet" type="text/css" /> <script type="text/j ...

Slider reset on postback, prevents slider from resetting on an ASP.NET website

I am facing an issue with a slider on my page. On page load, I have set a default value to the slider (25, 75). However, every time there is a postback inside the update panel after changing the slider value, it gets reset back to 25, 75. How can I prevent ...

Unable to determine the reason why the JavaScript plugin is not functioning as expected

I have been attempting to set up a JS modal window and have essentially copied the code for the plugin exactly as instructed, but it is not functioning properly. Here is my code... <!doctype html> <html> <head> <meta charset="utf- ...

Passing a property to a click event handler in ES6 with React: What's the best approach?

Struggling with passing props to a click function in my React learning journey. I'm attempting to make a basic ES6 counter component that increases when a button is clicked. The click function I have so far is: click() { this.setState({ c ...

Querying in mongodb based on a field in a referenced document: Tips and techniques

I am working with two collections in MongoDB - Products and Users. Each product document contains a field called ownerId which links to a user in the users collection. Additionally, each user has a Boolean field called isActive. My goal is to retrieve all ...

Understanding ReactJS's process of batching all DOM updates within a single event loop, ultimately minimizing the number of repaints needed

While perusing an article on DOM updates in ReactJS, I came across the concept of React updating all changes within a single event loop. Having a background in understanding event loops in JavaScript and how they function in core JavaScript, I am curious ...

Issue with padding in Material UI button component not being applied as expected

I am struggling with applying padding and styles to my Material UI component. Take a look at the code snippet below: import "./css/Landing.css"; import { Button } from "@mui/material"; function Landing() { return ( <div class ...

Customizing colors for the progress bar in Angular Material

In my Angular 5 project, I am using a material progress bar and hoping to customize the colors based on the percentage progress. Despite trying various methods from other sources (including previous SO questions), I have been unsuccessful in getting it to ...

Managing an unexpected variable when making an AJAX request

Here is a code snippet that I am working with: var User = { get: function (options) { var self = this; $.ajax({ url: options.url, success: function (data, response) { self.nextPageUrl = data.pagination.next_page; opt ...

Struggling to remove background image in WP CSS causing overlapping menus in submenu

I recently followed a tutorial on "Overlapping Tabs" for a WordPress project and found it to be quite helpful and functional. The tutorial can be viewed at After implementing the tabs from the tutorial, I decided to add dropdown submenus to enhance the fu ...

Converting this HTML/PHP code into JavaScript: A step-by-step guide

I have been struggling to convert this code into JavaScript in order to set the document.getElementById().innerHTML and display it in HTML. Can anyone assist with writing this code in JavaScript? <form action='create_new_invoice.php?name="<?php ...

stop an html page from opening a new window

When using my HTML-based application, there are instances when it needs to open another URL within an iframe. However, a problem arises when the third-party URL within the iframe also opens a new window with the same content and URL. How can I prevent th ...

Strategies for CSS Layout within Navigation Bars

Currently, I am in the process of learning how to create a responsive website by following a tutorial. You can find my demo project here, however, I seem to be encountering an issue. I am unable to place any content to the right of the <ul> within th ...

Ways to verify the content within two separate p elements

<p> expanded state:</p> <P> true </p> Merging the text from both tags into a single output. Final Output: expanded state: true ...

Can PhoneGap/Cordova's Media class bypass the restrictions of audio in HTML5 on iOS and Android devices?

After researching the limitations of html5 on iOS, I discovered that only one audio file can be played at a time and audio can only be triggered by user interaction. This is discouraging as I am working on creating a high-quality html5 game that requires b ...

Checking the authenticity of a JWT Token within the vue.js Router

Creating a JWT token using the code snippet below: jwt.sign(id, TOKEN_SECRET, { expiresIn: '24h' }); Once the token is generated, it is sent to the client and stored in a cookie like so: document.cookie = `session=${token}` + ';' + e ...

Dynamically divide canvas screens based on fabricjs dropdown selection

I am attempting to implement split screens in fabric js, such as 1, 2, 4, 8, and 16. The screen should split based on the selection from the dropdown menu. Check out my current code where I have successfully uploaded images. If I click on the images, th ...

Container filled with a table element

My challenge involves a container grid with 3 div flex subelements. The first is the fixed header, the second is the body, and the third is the fixed footer. Within the body, there is a table. What I want to achieve is that when I resize the window, the ta ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

All you need to know about the impressive world of HTML5

When the server sends coordinates for a shape like a rectangle, rhombus, circle, trapezium, or polygon and I am uncertain about which one will be received, how should I decide on the figure to draw on the canvas using the Angular framework? ...