The error message indicates that the element countdown is missing or does not exist

I typically refrain from discussing topics that I'm not well-versed in (my weak spot has always been working with time and dates in javascript), but I find myself in urgent need of assistance.

I've decided to use this link to showcase a countdown timer on my client's website. It seems like a simple task, right? Here's how I implemented it:

<script type="text/javascript">
// set the date we're counting down to
var target_date = new Date('Sep, 18, 2015').getTime();

// variables for time units
var days, hours, minutes, seconds;

// get tag element
var countdown = document.getElementById('countdown');

// update the tag with id "countdown" every 1 second
setInterval(function () {

    // determine the number of "seconds" between now and the target
    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;

    // perform some time calculations
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    // format the countdown string and set the tag value
    countdown.innerHTML = '<span class="days">' + days + ' <b>Days</b></span> <span class="hours">' + hours + ' <b>Hours</b></span> <span class="minutes">'
    + minutes + ' <b>Minutes</b></span> <span class="seconds">' + seconds + ' <b>Seconds</b></span>';  

}, 1000);
</script>

Style

<style>
.container {
  margin: 0px auto;
  padding: 0px;
}

#main { 
  background: #3B3B3B;
  height: 430px;
}

.content {
  padding: 10px 44px;
}

.text {
  border-bottom: 1px solid #262626;
  margin-top: 40px;
  padding-bottom: 40px;
  text-align: center;
}

.text h2 {
  color: #E5E5E5;
  font-size: 30px;
  font-style: normal;
  font-variant: normal;
  font-weight: lighter;
  letter-spacing: 2px;
}

.counter {
  background: #2C2C2C;
  -moz-box-shadow: inset 0 0 5px #000000;
  -webkit-box-shadow: inset 0 0 5px #000000;
  box-shadow: inset 0 0 5px #000000;
  min-height: 150px;
  text-align: center;
}

.counter h3 {
  color: #E5E5E5;
  font-size: 14px;
  font-style: normal;
  font-variant: normal;
  font-weight: lighter;
  letter-spacing: 1px;
  padding-top: 20px;
  margin-bottom: 30px;
}

#countdown {
  color: #FFFFFF;
}

#countdown span {
  color: #E5E5E5;
  font-size: 26px;
  font-weight: normal;
  margin-left: 20px;
  margin-right: 20px;
  text-align: center;
}
</style>

HTML

<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div id="main">
<div class="content">
<div class="text">
<h2>This Website Is Under Construction</h2>
</div><!-- /.Text Div -->
<div class="counter">
<h3>Estimated Time Remaining Before Launch:</h3>
<div id="countdown">
</div><!-- /#Countdown Div -->
</div><!-- /.Counter Div -->
</div> <-- /.Content Div -->
</div> <-- /#Main Div -->
</div> <-- /.Columns Div -->
</div> <-- /.Row Div -->
</div> <-- /.Container Div -->

Output

https://i.sstatic.net/hR88B.png

Firefox throws the following error:

https://i.sstatic.net/v3SpF.png

Chrome displays the following message:

https://i.sstatic.net/xdWqw.png

The code is identical to what I have provided above, yet I encounter the errors shown in the images attached. Interestingly enough, when using this fiddle I have created, everything works fine. Quite perplexing, don't you think?

Answer â„–1

Ensuring that your code runs after the document has fully loaded is crucial. Otherwise, the element with the ID may not exist yet when the code executes. In your case, the countdown variable will be null because the element hasn't been added to the document at the time of execution.

An easy workaround, as seen in your jsfiddle example (look at the source in the bottom right frame), is to place the <script> tag below the element so that the countdown element will likely exist when the code runs.

A more robust solution, especially since you have tagged your question with jQuery, would be to encapsulate your code within $(document).ready() or its shorthand:

$(function() {
  // Your code...
});

If compatibility with IE8 and below is not a concern, there is also a Vanilla JS alternative that you can consider.


Below is a runnable snippet showcasing the jQuery solution:

$(function() {
  var target_date = new Date('Sep, 18, 2015').getTime();
  var days, hours, minutes, seconds;
  var countdown = document.getElementById('countdown');

  setInterval(function () {

    // calculate the "seconds" remaining until the target date
    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;

    // perform time calculations
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    // format the countdown string and update the element's value
    countdown.innerHTML = '<span class="days">' + days +  ' <b>Days</b></span> <span class="hours">' + hours + ' <b>Hours</b></span> <span class="minutes">'
    + minutes + ' <b>Minutes</b></span> <span class="seconds">' + seconds + ' <b>Seconds</b></span>';  

  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Estimated Time Remaining Before Launch:</h3>
<div id="countdown"></div>


Here is another version that ensures the counter starts immediately instead of waiting for the first 1-second interval:

$(function() {
  var target_date = new Date('Sep, 18, 2015').getTime();
  var days, hours, minutes, seconds;
  var countdown = document.getElementById('countdown');

  function updateCounter() {

    // find the amount of "seconds" between now and target
    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;

    // do some time calculations
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    // format countdown string + set tag value
    countdown.innerHTML = '<span class="days">' + days +  ' <b>Days</b></span> <span class="hours">' + hours + ' <b>Hours</b></span> <span class="minutes">'
    + minutes + ' <b>Minutes</b></span> <span class="seconds">' + seconds + ' <b>Seconds</b></span>';  

  }
  
  updateCounter();
  
  setInterval(updateCounter, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Estimated Time Remaining Before Launch:</h3>
<div id="countdown"></div>

Answer â„–2

Is the JavaScript code being triggered after the document has finished loading? It appears you are trying to access a DOM element with the ID countdown, but it may not have been rendered yet.

Check out jQuery's document ready function for guidance.

In general, your code should resemble this:

    $( document ).ready(function() 
    {
        var target_date = new Date('Sep, 18, 2015').getTime();

        // variables for time units
        var days, hours, minutes, seconds;

        // get reference to the countdown element
        var countdown = document.getElementById('countdown');

        ... //etc...
    });

Answer â„–3

If you prefer not to use jQuery in this case, consider wrapping your setInterval method with a startCount function and triggering it with the body's onload event.

function startCount() {

    // update the tag with id "countdown" every 1 second
    setInterval(function () {

        // determine the number of seconds remaining until the target date
        var current_date = new Date().getTime();
        var seconds_left = (target_date - current_date) / 1000;

        // perform time calculations
        days = parseInt(seconds_left / 86400);
        seconds_left = seconds_left % 86400;

        hours = parseInt(seconds_left / 3600);
        seconds_left = seconds_left % 3600;

        minutes = parseInt(seconds_left / 60);
        seconds = parseInt(seconds_left % 60);

        // format countdown string + update tag value
        countdown.innerHTML = '<span class="days">' + days +  ' <b>Days</b></span> <span class="hours">' + hours + ' <b>Hours</b></span> <span class="minutes">'
        + minutes + ' <b>Minutes</b></span> <span class="seconds">' + seconds + ' <b>Seconds</b></span>';  

    }, 1000);

}

Include the following code in the body tag:

<body onload='startCount();'>

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

Is there a way to transform a Phaser 3 game into an android-game application?

As someone who is new to Phaser, I am curious about the possibility of converting a Phaser game into an Android game. Currently, I am utilizing Phaser with NPM for my projects. Any insights or advice on this matter would be greatly appreciated. Thank you! ...

Techniques for transferring information to Highchart directly from session storage

I am attempting to populate a pie highchart with data from a session storage variable, but I am not seeing any results. Here is the desired code: $(function () { Highcharts.chart('container', { chart: { type: 'pie', ...

What is the process for obtaining the URL of the website that is hosting my iframe?

Do you have a technical inquiry? I am curious to know if it is feasible to retrieve the URL of the website that is hosting my iframe. The pages that host my iframe are utilizing the following code: <iframe id="vacancy-iframe" src="http://mypage.co ...

Extracting pictures with py Jupyter

While attempting to scrape images from this URL using Python in Jupyter: https://www.adobe.com/products/catalog.html?sort=name&types=pf_252Fdesktop&types=pf_252Fmobile&types=pf_252Fweb&page=1, the code I ran resulted in the following error: ...

Encountering an issue: Unable to initiate a local server when running `npm start`

Currently diving into the world of React, I successfully set up a React app. However, upon running npm install after typing cd davidsapp, I encountered numerous warnings and errors. Subsequently, when issuing the command npm start, all of the errors are di ...

Change HTML canvas data into Angular form data before sending it to the Laravel backend

My JavaScript code to convert a data URL to blob and send it as a form request is: var canv = document.getElementById("mainCanvas"); var dataURL = canv.toDataURL('image/jpg'); documentData = {"image": dataURLtoBlob(dataURL), "gameName": "empero ...

What is the best way to send an error message and corresponding HTTP status code to trigger the jQuery AJAX error function?

With the use of Spring framework, I have implemented a SimpleMappingExceptionResolver to handle unexpected exceptions in my application. The resolveException method catches these exceptions and returns an error message back to the HTTP client through a Mod ...

What could be causing the CSS height percentage to malfunction?

I'm having trouble with some basic CSS that uses percentages. I've labeled everything and checked my code, but it still isn't working properly. Here's the CSS code snippet: .BoxHeight { height: 100%; } #Box { margin-top: 0%; mar ...

Is there a way to consistently apply default props to a styled component?

Currently, I am working with React, Material UI, and Styled Components. My goal is to create a personalized Input field where the size='small' is always passed as a prop to my component. To clarify, if the user neglects to include the size attri ...

Retrieve the most recently added item in the Material-ui Autocomplete component

Currently, I am incorporating the material-ui Autocomplete component with multiple selection feature. In one specific scenario, I require the ability to retrieve only the value of a newly added item. Despite utilizing the onChange listener, the event pro ...

Is there a way to submit a basic HTML form using R?

As a newcomer to R programming, I am excited to apply what I am learning in the Johns Hopkins Data Science track to practical use. My current goal is to automate the process of downloading historical bond prices from the US Treasury website After explorin ...

"Utilizing Vuex: Fetch data from API when the first getter is accessed, and subsequently retrieve it from the local

I have a Vuex instance that is responsible for fetching data from an API. The initial access to the store should trigger a call to load the data from the API. Subsequent accesses should return the previously loaded data stored in store.empresas. This is th ...

Manipulating the vueObject.dataItem variable in Vue JS directly affects the underlying Vue data item

I’ve encountered a troublesome behavior in my projects. Here is a simplified explanation of the issue at hand. I am eager to understand why this occurs and how I can prevent it. I have included Vue in the head section of my website: <script src="http ...

jQuery UI validation causing submission of a form with invalid data

Currently, I am troubleshooting an issue with a form that utilizes Ajax to submit data to the backend. For validation, I'm using the jQuery-ui validation plugin. The problem I am encountering is that the form submits even when fields are left empty. ...

The hue of the knob is unchangeable once the server data request is made

Upon receiving data from the server request, I am unable to update the color of the knob to match the image provided at this link screencast. Below is my code: JavaScript Code $scope.options = { /* knob option */ }; $http .get(url) .then(functio ...

Adding descriptive text before a website link is a helpful way to provide context for the reader. For example

My goal is not just to have JavaScript change the URL after my page has loaded. I want to be able to enter something like 'blog.mywebsite.com' into the omnibar and have it locate my website similar to how Steam does with 'store.steampowered. ...

Performing the AJAX request prior to the document being fully loaded

What I need is for an AJAX call to be made before the document is ready, and then use the response from the AJAX call to update certain HTML elements. This is what I currently have: var ajaxget = $.ajax({ type: 'GET', url:'/xxx ...

Incorporating Mongoose Schema structures into my NextJS webpage

I am new to NextJS and seeking assistance with an issue I am facing. I have defined 2 Mongoose schemas and using one on my page without any problems. However, when I try to import the second schema, my page fails to render and throws an error. Regardless ...

What is the best method to calculate the dimensions of flex items without relying on percentages?

Imagine this as the structure of my HTML, with an unspecified number of div elements: <body> <div></div> <div></div> <div></div> <div></div> <div></div> <div>& ...

Encountering difficulties while trying to integrate a material view in Angular 6, facing the following error

After creating a page using angular 6, I attempted to implement material view for the UI. However, during the implementation process, I encountered the following error: Despite trying to add the material.js lib, I was unable to resolve the issue. An er ...