What is the reason for the countdown number's color remaining the same even after it reaches a specific time threshold?

Creating a simple countdown for sports was my idea, but now I'm stuck on the "changeColor" part that I don't have enough knowledge about.

The countdown is functioning perfectly, but customizing the colors and adding CSS animations seems challenging to me. The issue arises with the last part "changeColor".

For instance, when inputting 60s, it should turn green. If inputted as 29s, it should change to orange. And if entered as 9s, it needs to switch to red.

However, why doesn't it automatically change when going from 30 seconds to 29? It should become orange at that point. The same applies for the transition from 10 to 9 seconds, where it should start blinking and turn red, yet nothing happens.

Below is the script:

var CCOUNT;
$(document).ready(function () {
    $('#btnct').click(function () {
        CCOUNT = $('#seconds').val();
        cdreset();
    });
});
var t, count;

function cddisplay() {
    document.getElementById('timespan').innerHTML = count;

}

function countdown() {
    // starts countdown
    cddisplay();
    changeColor(CCOUNT);
    if (count === 0) {
        // time is up
    } else {
        count--;
        t = setTimeout(countdown, 1000);

    }
}

function cdpause() {
    // pauses countdown
    clearTimeout(t);
}

function cdreset() {
    // resets countdown
    cdpause();
    count = CCOUNT;
    cddisplay();
}

function changeColor() {
if (CCOUNT <= 1000 && CCOUNT > 30) {
document.getElementById('counting1').style.color = "#00CC00";

}

else if (CCOUNT <= 30 && CCOUNT > 10) {
document.getElementById('timespan').style.color = "#F87217";
}

else {
document.getElementById('timespan').style.color = "#ff0000";
document.getElementById('timespan').css = ({"text-decoration": "blink", "-webkit-animation-name": "0.2s", "text-decoration": "blink", "-webkit-animation-iteration-count": "infinite", "-webkit-animation-timing-function": "ease-in-out", "-webkit-animation-direction": "alternate"});
}
}

I've made it live on baswijdenes.com/simple-countdown for you to view.

EDIT: Here's the HTML code:

<center>
<form id="frm">
  <div class="counting">  
    <input type="text" class="input" id="seconds" name="seconds" value="0" size="2" maxlength="4" />    

    </div>
    <input type="button" class="btn blue" id="btnct" value="Input" />

</form>

<div class="counting1" id="counting1">
<span type="text" id="timespan">0</span>
</div>
<BR>
<BR>
<div id="divaroundbuttons">
<input type="button" class="btn green" value="Start" onclick="countdown()">
<input type="button" class="btn orange" value="Stop" onclick="cdpause()">
<input type="button" class="btn red" value="Reset" onclick="cdreset()">
</div>
</center>

Answer №1

During my debugging process, I encountered two variables that caused confusion:

  • CCOUNT
  • count

Upon modifying the function countdown() and introducing a console.log(CCOUNT) to monitor the count, it became evident that CCOUNT was not decreasing as expected. After replacing CCOUNT with count, I observed that while the displayed number changed color, it remained fixed.

As a potential solution, I recommend updating the countdown logic to decrement both CCOUNT and count simultaneously:

function countdown() {
    // initiates countdown
    cddisplay();
    changeColor(CCOUNT);
    if (CCOUNT === 0) {
        // timer is up
    } else {
        CCOUNT--;
        count--;
        t = setTimeout(countdown, 1000);

    }
}

Another issue arises with the changeColor() function, where you mentioned the color should switch at 29 and 9 seconds, not 30 and 10 seconds.

I trust this information will be of assistance.

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

How can we validate the radio buttons to show a value even if none of the buttons are checked?

In my registration form, I have a gender radio option with "male" or "female" choices. Both options are unchecked initially so the user must select one. Here is the HTML code: <label class="radio"> <input type="radio" name="gender" id="option ...

Creating an animated CSS growth effect using inline SVG

I'm trying to make these circuits look like they are running downwards. I have the right movement, but I can't seem to start them at their actual size, causing them to appear skewed at the beginning of the animation and then scaling to full size ...

"Encountered a 404 Error while attempting an Ajax

I am relatively new to web development and I am currently working on making a post method function properly. Below is the ajax call that I have implemented: $.ajax({ type: "POST", url: '/Controllers/AddPropertyData', ...

The table is not properly displaying within the parent scrolled div due to issues with the fixed positioning

Apologies for any language barrier. I am encountering an issue with a PHP page that includes a table meant to be displayed as position:fixed; however, it consistently appears above the scrollbars and does not stay within the parent div. View screenshot he ...

Archive a webpage with refreshed content using ajax

Is there a way to save a webpage that has been updated through an ajax request? I'm looking to preserve basecamp message threads, but exporting is not possible since I am not the account owner. When attempting to use the javascript command below: jav ...

Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText&g ...

Creating formatted code blocks within my HTML document

I'm currently working on achieving this layout in my HTML: https://i.stack.imgur.com/2LEQO.png Here is the JSFiddle link: https://jsfiddle.net/cr9vkc7f/4/ I attempted to add a border to the left of my code snippet as shown below: border-left: 1px ...

Do not directly change a prop - VueJS Datatable

Just starting out on Vue JS and encountered an issue while trying to create a Data Table by passing parent props to child components. An Error Occurred: [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent ...

Utilizing multiple classes in HTML for a button element

  I've recently come across the concept that elements can have multiple classes. It's interesting, isn't it? .rfrsh-btn { background-image:url(../../upload/rfrsh_nb_grey.png); ... } .submit { font-size: 0.85em; paddi ...

Using Vue.js to showcase real-time Pusher data in Laravel 5.4

I am currently working on developing a real-time chat application using vue.js, Pusher, and Laravel. I have successfully managed to receive information from Pusher, as I can view the JSON data in the console with the correct details. However, I am facing a ...

Whenever I try to send an email in Node.js, I encounter 404 errors. Additionally,

I have an Angular application with a form that makes AJAX requests. Emailing works fine, but no matter what I set the response to, I get an error for the path '/send'. I assume Node.js expects the path '/send' to render a template or da ...

C++ displaying results through web interfaces

Is it possible to write a C++ program that displays "Hello World!" on a webpage? #include <iostream> using namespace std; int main () { cout << "Hello World!"; return 0; } And is it possible to integrate this program into an HTML webpage ...

The useEffect hook is failing to trigger

Currently, I am attempting to retrieve data from an API using Redux for state management. Despite trying to dispatch the action within the useEffect hook, it does not seem to be functioning properly. I suspect that the issue lies with the dependencies, but ...

Creating an accessible order for the next and back buttons

Currently, I am working on designing the user interface for a checkout flow. Towards the end of the page, there are 3 buttons available - Next, Back, and Cancel. When viewed on a desktop, the button layout appears as follows: (Back) (Next) Cancel http ...

Steps for modifying the documents on an osCmax website

I had a developer set up my website in osCmax a while ago, and now I want to update the design of some pages using HTML and CSS on my own. While I am comfortable with HTML and CSS, I have very limited knowledge of PHP. This is my first attempt at working o ...

MUI full screen dialog with material-table

Issue: When I click a button on my material-table, it opens a full-screen dialog. However, after closing the dialog, I am unable to interact with any other elements on the screen. The dialog's wrapper container seems to be blocking the entire screen. ...

PHP - contact form is live for just 2 hours daily

Hello, this is my first time here and I could really use some assistance. Please bear with me as English is not my strong suit compared to most people here, but I'll do my best to explain my query. So, I have a PHP script for a contact form on my web ...

Develop a custom dropdown menu using JavaScript

I've been working on creating a dropdown menu that appears after selecting an option from another dropdown menu. Here's the HTML code I'm using: <br> <select id ="select-container" onchange="addSelect('select-container') ...

Preserve input values after form submission in <?php> code block

I would like to retain form values after submission. I have come across some techniques that claim to do just that: However, when I try to run the HTML file, I encounter two issues: firstly, the code does not function as intended and secondly, PHP snippet ...

Interfacing my Node.js REST API with AngularJS

I've got angular code that works with a local JSON file: App.controller('bodyController', ['$scope','$http',function($scope,$http){ $http.get('data.json').success(function(data){ $scope.data=data; }).error ...