Customizing the appearance of a JavaScript countdown timer's output on an individual basis

I am currently working on customizing the appearance of a JavaScript date counter. My goal is to style the days, hours, minutes, and seconds individually. Ideally, I want each unit to be right-aligned within its own div, with specific left and top absolute values. However, when I attempted to implement this, the timer did not replace the previous numbers as expected, resulting in a messy display.

Below is the code snippet that contains the output I am trying to customize:

document.getElementById(id).innerHTML = days + 'days ';
document.getElementById(id).innerHTML += hours + 'hrs ';
document.getElementById(id).innerHTML += minutes + 'mins ';
document.getElementById(id).innerHTML += seconds + 'secs';

Here's a fiddle where the counter works correctly but lacks separate styling

However, my attempts to place each unit in separate divs resulted in unexpected behavior, as the counter failed to update and simply added numbers instead. Here's a fiddle demonstrating this issue

Can anyone advise me on how to achieve the desired custom styling for the JavaScript date counter?

Answer №1

When adding the innerHTML values to the div, you should enclose them in a span with a specified class.

Check out the JSfiddle demo here

document.getElementById(id).innerHTML = '<span class="days">' + days + 'days ';
document.getElementById(id).innerHTML += '<span class="hours">' + hours + 'hrs ';
document.getElementById(id).innerHTML += '<span class="minutes">' + minutes + 'mins ';
document.getElementById(id).innerHTML += '<span class="seconds">' + seconds + 'secs';

CountDownTimer('01/01/2016 10:01 AM', 'countdown');

function CountDownTimer(dt, id) {
  var end = new Date(dt);

  var _second = 1000;
  var _minute = _second * 60;
  var _hour = _minute * 60;
  var _day = _hour * 24;
  var timer;

  function showRemaining() {
    var now = new Date();
    var distance = end - now;
    if (distance < 0) {

      clearInterval(timer);
      document.getElementById(id).innerHTML = 'EXPIRED!';

      return;
    }
    var days = Math.floor(distance / _day);
    var hours = Math.floor((distance % _day) / _hour);
    var minutes = Math.floor((distance % _hour) / _minute);
    var seconds = Math.floor((distance % _minute) / _second);

    document.getElementById(id).innerHTML = '<span class="days">' + days + 'days ';
    document.getElementById(id).innerHTML += '<span class="hours">' + hours + 'hrs ';
    document.getElementById(id).innerHTML += '<span class="minutes">' + minutes + 'mins ';
    document.getElementById(id).innerHTML += '<span class="seconds">' + seconds + 'secs';
  }

  timer = setInterval(showRemaining, 1000);
}
#countdown {
  position: absolute;
  z-index: 5;
  left: 20px;
  top: 20px;
  color: #ff0000;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 32px;
  display: inline;
}
.days {
  color: lightblue;
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
  padding: 10px;
}
.minutes {
  color: tomato;
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
  padding: 10px;
}
.seconds {
  color: gray;
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
  padding: 10px;
}
.hours {
  color: tomato;
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
  padding: 10px;
}
<div id="countdown">


</div>

Answer №2

By simply removing the line

document.getElementById(id).innerHTML = days + 'days ';

You will avoid "creating a big mess.". It's important to clear the div before adding new content.

document.getElementById(id).innerHTML = '';

Answer №3

Why not distribute your time elements among four distinct div containers within the existing one, instead of consolidating them under a single ID? By employing getElementById, you can then place each time element into its respective sub-division.

This approach enables you to apply unique styling using CSS for each individual time element.

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

Deactivate a button when clicked on a card that has been mapped

After creating a card component and mapping through each card, I added an onClick function to disable the button of the clicked card. However, my logic ended up disabling all buttons instead. Here is the code snippet where I define the rendering of the UI ...

Target specifically the onhover div element using JQuery and trigger the smooth sliding down effect with the SlideDown() function

Is it possible to create a unique JQuery slidedown() function that will only be applied to the div where the mouse is hovering? I have managed to make it work by giving each div a separate class, but when I name them all the same, it triggers the slide do ...

The key to highlighting the search terms in bold format

How can I highlight the search terms entered by users in the search box? I want all keywords in every search result to be bolded. For example, when a search term is entered and the results page displays all results with the typed term in bold within each ...

Utilizing the fs module in Node.js

Hello friends! Currently I am faced with an issue while trying to import the fs module in nodejs. Initially, I utilized require to import it like so: const fs = require('fs'); Everything was functioning smoothly until recently when it suddenly ...

TinyMCE toolbar missing the "hr" option

I am encountering an issue while using TinyMCE as my editor. I have added the plugin as instructed, but I cannot find the "hr" button/option in the editor interface. If anyone has any insights or solutions to this problem, please share! This is how I am ...

Error TS7053 occurs when an element is given an 'any' type because a 'string' expression is being used to index an 'Object' type

When attempting to post data directly using templateDrivenForm and retrieve data from Firebase, I encountered the following type error message. Here are the relevant parts of my code: // Posting data directly using submitButton from templateDrivenForm onC ...

Creating a type definition for the createSelector function based on the useQuery result

Struggling to find the correct typings for the createSelector res parameter from redux-js, especially in TypeScript where there are no examples or explanations available. The only guidance is provided in JS. const selectFacts = React.useMemo(() => { ...

gRaphael - the struggle of animating a line chart

Encountering an issue with the gRaphael javascript line chart library. Creating a line chart from a CSV file with five columns (# of minutes, time, waiting time, in treatment, closed, in location). Previously drew full chart without animation successfull ...

Troubleshooting server-side sorting issues with AJAX implementation, encountering problems with headers functionality

I'm encountering a problem: Some headers are not functioning properly to sort the table. For example, Brand and Model work as expected, but VehicleType only works once, and CarID and ReleaseDate never seem to work. Here is my index.php file: index. ...

Ensure that the child element completely fills the parent element while maintaining a padding around the edges

How can I create a child div that fills 100% of the parent's width and height, including padding? I've tried using box-sizing = border-box, but it isn't working. I also attempted adding the box-sizing property to all elements with *, but tha ...

"Creating an array object in the state of Reactjs - a step-by-step

As I am delving into the world of ReactJS, I am learning about changing state within this framework. One challenge I encountered was initializing an array object in state with an unknown length and updating it later using setState. Let me share the snippet ...

I want to hide jqvmap when viewing on mobile devices

I'm currently working on my website at . I have a template that I'm using as a guide, but I want to make the map disappear on mobile view and replace it with a dropdown list. Can anyone suggest what code I should use for this? Appreciate any hel ...

Hexagonal Shape with Rotating Border Gradient in CSS

Looking to create a hexagon shape with a rotating gradient border. Here's an example GIF for reference: https://i.stack.imgur.com/Ah1AO.gif I attempted using CSS only but the use of :after and :before tags proved limiting since they rely on border s ...

Set a value for the hidden field on the page using client-side scripting

When working with an ASP.net application, I often use Page.ClientScript.RegisterHiddenField("hf_Name", value). However, I am curious about how to override or set a new value for the same Hidden Field 'hf_Name' in the code behind. Can you provide ...

Adjusting a NodeJS module for easier integration into codebases

I have organized some functions in a file within a node module structure... Here are the files and folder structure I created: - package.json - README.md - LICENSE.md - code |_______ code.js Currently, to use these functions, I include them like th ...

Does the Mirage addon work effectively in the ember.js tutorial?

Following the ember.js tutorial, I'm facing a roadblock at this particular stage: (especially when implementing the Mirage add-on). I've made changes to the mirage/config.js file as advised but still unable to display the Mirage data. Despite ...

What could be causing my Apollo useLazyQuery to be triggered unexpectedly within a React hook?

import { useLazyQuery } from '@apollo/client'; import { useEffect, useState } from 'react'; import { ContestSessionResponseInfoObject, GetSessionDocument, HasAccessToRoundDocument, } from '@/graphql/generated/shikho-private- ...

Navigation that remains fixed while scrolling

Can someone help me fix the side navigation of this template to stay fixed when a user scrolls past it for easier navigation? I'm struggling with the code and could use some fresh eyes to look at it. I just can't seem to figure it out on my own, ...

Add slides in PowerPoint before or after the currently selected slide to enhance your presentation flow

I'm currently working on a function that pulls data from an API to convert PowerPoint presentations into base64 strings. Once I receive the response object, my goal is to seamlessly insert the slides into the existing presentation, exactly after the s ...

How can Spring and AngularJS (HTML) work together to retrieve the Context Path?

Currently, I am working with Spring and AngularJS. I haven't encountered any issues displaying my index.html using Spring in the following way: @RequestMapping(value="/") public String index() { return "/app/index.html"; } Is there a way for me ...