Step-by-step guide on repairing a countdown clock using JavaScript, HTML, and

I'm having issues with my JS on my website. I am new to this and currently in the process of setting up a website. I want to add a timer to show when the site will be active.

It seems like there is an error somewhere in the JS code that I can't quite pinpoint. Since I don't have much experience with JS, I'm struggling to understand what's causing the problem.

At the moment, I just need help figuring out why the script isn't working. Once I grasp how the code connects to the HTML, I'll dive into understanding its functionality.

Any assistance would be greatly appreciated.

  
        var target_date = new Date().getTime() + (1000*3600*48); // set the countdown date
        var days, hours, minutes, seconds; // variables for time units
        
        var countdown = document.getElementById("tiles"); // get tag element
        
        getCountdown();
        
        setInterval(function () { getCountdown(); }, 1000);
        
        function getCountdown(){
        
        // find the amount of "seconds" between now and target
        var current_date = new Date().getTime();
        var seconds_left = (target_date - current_date) / 1000;
        
        days = pad( parseInt(seconds_left / 86400) );
        seconds_left = seconds_left % 86400;
         
        hours = pad( parseInt(seconds_left / 3600) );
        seconds_left = seconds_left % 3600;
          
        minutes = pad( parseInt(seconds_left / 60) );
        seconds = pad( parseInt( seconds_left % 60 ) );
        
        // format countdown string + set tag value
        countdown.innerHTML = "<span>" + days + "</span><span>" + hours + "</span><span>" + minutes + "</span><span>" + seconds + "</span>"; 
        }
        
        function pad(n) {
        return (n < 10 ? '0' : '') + n;
        }
                body
                {
                width:1000px;
                height:1000px;
                position:relative;
                top:10px;
                margin:auto;
                background-image:url('bg copy.png');
                }
                
                #Header
                {
                width:1000px;
                background-image:url('Logo 3 small.png');
                background-repeat:no-repeat;
                background-position:center;
                }
                
                #Middle
                {
                width:1000px;
                }
                
                #Soon
                {
                height:100px;
                width:1000px;
                font-family:"Malgun Gothic Semilight";
                font-size:20px;
                color:Black;
                
                }
                
                #Timer
                {
                height:200px;
                width:1000px;
                }
                
                #Bottom
                {
                font-size:80px;
                }
                

                #countdown{
                width: 465px;
                height: 112px;
                text-align: center;
                background: #222;
                background-image: -webkit-linear-gradient(top, #222, #333, #333, #222); 
                background-image:    -moz-linear-gradient(top, #222, #333, #333, #222);
                background-image:     -ms-linear-gradient(top, #222, #333, #333, #222);
                background-image:      -o-linear-gradient(top, #222, #333, #333, #222);
                border: 1px solid #111;
                border-radius: 5px;
                box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.6);
                margin: auto;
                padding: 24px 0;
                position: absolute;
                  top: 0; bottom: 0; left: 0; right: 0;
                }
                
                #countdown:before{
                content:"";
                width: 8px;
                height: 65px;
                background: #444;
                background-image: -webkit-linear-gradient(top, #555, #444, #444, #555); 
                background-image:    -moz-linear-gradient(top, #555, #444, #444, #555);
                background-image:     -ms-linear-gradient(top, #555, #444, #444, #555);
                background-image:      -o-linear-gradient(top, #555, #444, #444, #555);
                border: 1px solid #111;
                border-top-left-radius: 6px;
                border-bottom-left-radius: 6px;
                display: block;
                position: absolute;
                top: 48px; left: -10px;
                }
                
                #countdown:after{
                content:"";
                width: 8px;
                height: 65px;
                background: #444;
                background-image: -webkit-linear-gradient(top, #555, #444, #444, #555); 
                background-image:    -moz-linear-gradient(top, #555, #444, #444, #555);
                background-image:     -ms-linear-gradient(top, #555, #444, #444, #555);
                background-image:      -o-linear-gradient(top, #555, #444, #444, #555);
                border: 1px solid #111;
                border-top-right-radius: 6px;
                border-bottom-right-radius: 6px;
                display: block;
                position: absolute;
                top: 48px; right: -10px;
                }
                
                #countdown #tiles{
                position: relative;
                z-index: 1;
                }
                
                #countdown #tiles > span{
                width: 92px;
                max-width: 92px;
                font: bold 48px 'Droid Sans', Arial, sans-serif;
                text-align: center;
                color: #111;
                background-color: #ddd;
                background-image: -webkit-linear-gradient(top, #bbb, #eee); 
                background-image:    -moz-linear-gradient(top, #bbb, #eee);
                background-image:     -ms-linear-gradient(top, #bbb, #eee);
                background-image:      -o-linear-gradient(top, #bbb, #eee);
                border-top: 1px solid #fff;
                border-radius: 3px;
                box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.7);
                margin: 0 7px;
                padding: 18px 0;
                display: inline-block;
                position: relative;
                }
                
                #countdown #tiles > span:before{
                content:"";
                width: 100%;
                height: 13px;
                background: #111;
                display: block;
                padding: 0 3px;
                position: absolute;
                top: 41%; left: -3px;
                z-index: -1;
                }
                
                #countdown #tiles > span:after{
                content:"";
                width: 100%;
                height: 1px;
                background: #eee;
                border-top: 1px solid #333;
                display: block;
                position: absolute;
                top: 48%; left: 0;
                }
                
                #countdown .labels{
                width: 100%;
                height: 25px;
                text-align: center;
                position: absolute;
                bottom: 8px;
                }
                
                #countdown .labels li{
                width: 102px;
                font: bold 15px 'Droid Sans', Arial, sans-serif;
                color: #f47321;
                text-shadow: 1px 1px 0px #000;
                text-align: center;
                text-transform: uppercase;
                display: inline-block;
            <head>
            <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
            <title>SPAutoTech Home</title>
            <link href="localcss.css" rel="stylesheet" type="text/css" />
            <script src="jquery-3.4.0.min.js"></script>
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
            <script src="java.js"></script>
            </head>
            
            <body>
            
            <div id="Header" style="height:400px">
            </div>
            
            <div id="Middle" style="height:300px">
            
            <div id="Soon">
            </div>
              
            <div id="counter">
            <div id="countdown">
              <div id='tiles'></div>
              <div class="labels">
                <li>Days</li>
                <li>Hours</li>
                <li>Mins</li>
                <li>Secs</li>
              </div>
            </div>
             </div>
            <script src="java.js"></script>
            
            <div id="Bottom" style="height:300px">
             
            </div>
            </div>
            
            <div id="Bottom1" style="height:300px">
            <center><b>COMING SOON</b></center>
            </div>
            
            </body>
            
            </html>

Answer №1

The <script> section with your countdown code should be placed in your HTML document before the closing <body> tag. Currently, you are using:

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

However, at this stage of page processing, the content inside the body has not been parsed yet, resulting in countdown being null. Consequently, when trying to set the .innerHTML of countdown:

countdown.innerHTML = "<span>" + days + "</span><span>" + hours + "</span><span>" + minutes + "</span><span>" + seconds + "</span>";

This operation fails because countdown was not found.

SOLUTION:

Move the entire <script> section so that it appears just before the closing body tag (</body>) since, by then, all the HTML will have been parsed.

Alternatively...

If you continue to use JQuery, you can enclose all the contents of your <script> within JQuery's document.ready method to ensure that your code executes only after the document has been fully parsed:

<script>
  $(document).ready(function(){
     // Place all your code here

  });
</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

What is the best way to navigate back to the top of the page once a link has been clicked?

One issue I'm facing is that whenever I click on a link in NextJS, it directs me to the middle of the page: <Link href={`/products/${id}`} key={id}> <a> {/* other components */} </a> </Link> I believe the problem l ...

Unable to open modals in Bootstrap using jQuery script: modal not popping up

My attempt to create functionality for two buttons and two modals - reserve a campsite (id="reserveButton" should open id="reserveModal") and Log in (id="loginButton" should open id="loginModal") is not working. I ha ...

Using AngularJS ng-repeat with jQuery find yields a single element result

I'm in the process of developing my very first AngularJS application, and I've run into an issue with the jQuery find function. Essentially, what I'm attempting to do is utilize a custom HTML component that contains a list of buttons generat ...

Gliding along a div and concealing it out of view, making it seem like it has disappeared

I attempted to slide down the ".preloader" div after a 2-second delay using JQUERY, but I couldn't get it to work as expected. I didn't want to use a toggle button for this effect. I also experimented with creating an animation using @keyframes, ...

Setting up parameters and arguments in Vuex mutations: A guide

I am currently developing a todo list application using Vue.js, Vuex, and Firebase. The functionality of the app seems to be in working order with the Store file effectively managing the retrieval and display of entered todo items to and from Firestore. Ho ...

Adjust Fabric js Canvas Size to Fill Entire Screen

Currently, I am working with version 4.3.1 of the Fabric js library and my goal is to adjust the canvas area to fit its parent div #contCanvasLogo. I have tried multiple approaches without success as the canvas continues to resize on its own. Below is the ...

Is it true that Internet Explorer does not support border radius?

Styling with CSS border-bottom: 1px solid silver; background-color: #000; background: rgb(51,51,51); /* Old browsers */ background: -moz-linear-gradient(top, rgba(51,51,51,1) 0%, rgba(153,153,153,1) 100%); /* FF3.6+ */ background: -webkit-gradient(linear, ...

Differences between ajax.actionlink replace and replacewithWhen it comes

Within my ASP.NET-MVC application, I am utilizing Ajax.ActionLink in a view and have opted for InsertionMode.Replace. However, I recently came across the ReplaceWith option. Can anyone clarify the distinction between the two? Does one offer a more comprehe ...

The alternative text for the oversized image exceeds the boundaries

After setting the width and height for an image, along with testing overflow:hidden, I've encountered an issue where the alt text for a broken image overflows the bounds of the image and the image size is lost. How can I contain the alt text within th ...

Retrieve information using AngularJS only when it is not yet defined

Currently, I am using $http in a controller to retrieve data and display it to the user. However, once the data is fetched for the first time, I do not want to fetch it again when moving between different tabs or controllers. My expertise lies in web dev ...

What to do when VueJs computed method throws an error: "Cannot access property 'words' of undefined"?

Here is some pseudo code that I've written: var vm = new Vue({ el: '#test', data: { words: [{name:'1'}, {name:'2'}, {name:'3'},{name:'4'},{name:'5'},{name:'6'}], } ...

Progressively updating elements one by one leads to updates

I am currently working on a webpage where one element ('.item--itemprice') updates its text through a function that I don't want to modify. My goal is to have another element ('.header--itemprice') update its text to match the firs ...

Passing data from an arraylist to an Ajax success callback function

Help me troubleshoot an issue with my AJAX success function. I'm trying to retrieve data from an ArrayList and populate text fields based on the ID passed through AJAX. Although everything seems fine, the data is not displaying in the text fields. Whe ...

Expanding and collapsing multiple rows within a Bootstrap grid

Seeking advice on Bootstrap and its implementation of columns and rows. Currently facing a cascading effect where I have managers, followed by employees, and then employee family members. The challenge lies in my limited understanding of how Bootstrap uti ...

What is the significance of the A tag when parsing a URL?

So, I encountered a problem that involved parsing a URL to extract the hostname and pathname, then comparing the extracted pathname with a string. If you need help with this issue, check out this post: How do I parse a URL into hostname and path in javasc ...

Backend framework

Currently, I am in the process of developing a robust web application that heavily relies on JavaScript and jQuery, with ajax functionality included. Additionally, there will be a database in place, managed using mySQL with several tables. I'm undeci ...

The Precision of the IRR (Internal Rate of Return) Calculation in Javascript

I've been working on a custom IRR function in JavaScript to mimic the functionality of Excel's IRR function. Despite my best efforts, it seems that my results are slightly off. Below is the code snippet that I have been using: var IRRval = []; ...

Collaborate on sharing CSS and TypeScript code between multiple projects to

I am looking for a solution to efficiently share CSS and TS code across multiple Angular projects. Simply copy-pasting the code is not an ideal option. Is there a better way to achieve this? ...

Retrieve the child element index of a specific element using jQuery

I am dealing with a group of 'DIV' elements, each containing a list of 'p' elements. Take a look at the example below: <div class="container"> <p>This is content 1</p> <p>This is content 2</p> ...

Looking for a way to access the source code of a QML method in C++?

I'm currently working on serializing objects to QML and I am looking for a way to retrieve the source code of functions defined within a QML object. Let's consider the following example in QML (test.qml): import QtQml 2.2 QtObject { functio ...