Dilip Posted May 6 Share Posted May 6 Hi, this is a beginner-level question. Please don't mind I have an index.html and script.js. I have included script.js in index.html. I am building a countdown timer. The script.js has values like const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24)); const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000); How do I call days, hours, minutes etc to the index.html separately so that I can style the countdown timer? Say <div class="red">days</div> <div class="green">hours</div> ... etc Thanks Quote Link to comment https://forums.phpfreaks.com/topic/320422-pulling-values-from-scriptjs/ Share on other sites More sharing options...
requinix Posted May 6 Share Posted May 6 How do you "call" them? What's the rest of the code? Is script.js meant to directly manipulate index.html or is it a utility thing and index.html has its own Javascript code? Is your question about how to get those values into index.html or is it how to get those values into the HTML itself? Quote Link to comment https://forums.phpfreaks.com/topic/320422-pulling-values-from-scriptjs/#findComment-1623361 Share on other sites More sharing options...
Dilip Posted May 6 Author Share Posted May 6 Hi, attaching all the files, please check <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Countdown Timer</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400&display=swap" rel="stylesheet"> <link href="/style.css" rel="stylesheet"> </head> <body> <div class="container my-5"> <h1>Countdown Timer</h1> <br> <br> <h4 class="text-success">Contest Ends on 31st May 2024 GMT at 11:59:59 PM</h4> <br> <p>Time Now in GMT :</p> <p class="text-success" id="nowtimeutc"></p> <br> <p>Contest Ends on (your date)</p> <br> <div id="yourdate"></div> <br> <div class="text-danger fs-1" id="expired"></div> <br> <p>Time left, the contest ends in</p> <br> <!-- <h2 class="text-danger fs-1" id="countdown"></h2> --> <br> <div class="container text-center"> <div class="row"> <div class="col"> <div class="fs-1" id="daysleft"></div>days </div> <div class="col"> <div class="fs-1" id="hoursleft"></div>hours </div> <div class="col"> <div class="fs-1" id="minutesleft"></div>minutes </div> <div class="col"> <div class="fs-1" id="secondsleft"></div>seconds </div> </div> </div> </div> <script src="/script2.js"></script> </body> </html> let endingDate = new Date(Date.UTC(2024, 4, 31, 23,59,59)); // Enter the date in UTC console.log(endingDate); let yourDate = document.getElementById("yourdate"); // Get te date in your time zone yourDate.textContent = endingDate; let now = new Date(); // time now console.log(now); let difference = endingDate.getTime() - now.getTime(); // Difference between target time and time now, in milliseconds console.log(difference); // Time now in UTC timeNow = new Date().toUTCString(); //timeNow = Math.floor((new Date()).getTime() / 1000); let nowTime = document.getElementById("nowtimeutc"); nowTime.textContent = timeNow; // Main function function displayCountdown(){ // input area start let endingDate = new Date(Date.UTC(2024, 4, 31, 23,59,59)); // Enter the date in UTC console.log(endingDate); let yourDate = document.getElementById("yourdate"); // Get te date in your time zone yourDate.textContent = endingDate; let now = new Date(); // time now console.log(now); let difference = endingDate.getTime() - now.getTime(); // Difference between target time and time now, in milliseconds console.log(difference); // input area ends let days = Math.floor(difference / 86400000); // divide Difference in milliseconds by no. of millisecond in a day to get days left console.log(days); let hours = Math.floor((difference % 86400000) / (1000 * 60 * 60)); // To get hours use modulus, get the time remaining after "days" and find how many hours in it console.log(hours); let minutes = Math.floor(((difference % 86400000) % (1000 * 60 * 60)) / (1000 * 60)); // finding minutes left - in effect hours - minutes in milliseconds console.log(minutes); let seconds = Math.floor((((difference % 86400000) % (1000 * 60 * 60)) % (1000 * 60)) / 1000); console.log(seconds); //let displayCount = `${days} days ${hours} hours ${minutes} minutes ${seconds} seconds`; //document.getElementById("countdown").innerHTML = displayCount; //setTimeout(displayCountdown, 1000); // Refreshes every 1 seconds //console.log("refreshed"); //Handling values individually // days const element = document.getElementById("daysleft"); element.textContent = days; document.getElementById("daysleft").innerHTML = myDays; setTimeout(myDays, 1000); // Refreshes every 1 seconds const element2 = document.getElementById("hoursleft"); element2.textContent = hours; document.getElementById("hoursleft").innerHTML = myHours; setTimeout(myHours, 1000); // Refreshes every 1 seconds const element3 = document.getElementById("minutesleft"); element3.textContent = minutes; document.getElementById("minutesleft").innerHTML = myMinutes; setTimeout(myMinutes, 1000); // Refreshes every 1 seconds const element4 = document.getElementById("secondsleft"); element4.textContent = seconds; document.getElementById("secondsleft").innerHTML = mySeconds; setTimeout(mySeconds, 1000); // Refreshes every 1 seconds }; // check if the time difference is valid if (difference <= 0) { console.log("Contest Finished, time expired"); let expiredContest = "Contest Finished, entry time expired"; document.getElementById("expired").innerHTML = expiredContest; } else { //setTimeout(displayCountdown, 500); // Call updateCountdown again every second } // setInterval(displayCountdown, 100); // Refreshes every 5 seconds // To stop the automatic execution: //clearInterval(intervalId); //setTimeout(displayCountdown, 1000); // Refreshes every 1 seconds displayCountdown(); console.log("printed"); }; //displayCountdown(); Quote Link to comment https://forums.phpfreaks.com/topic/320422-pulling-values-from-scriptjs/#findComment-1623362 Share on other sites More sharing options...
Danishhafeez Posted May 9 Share Posted May 9 It seems like you're almost there! Your code looks good, but there are a few adjustments needed to properly update the countdown timer in your HTML. // Main function to update countdown timer function updateCountdown() { // Calculate the time difference between now and the ending date let difference = endingDate.getTime() - new Date().getTime(); // Check if the difference is valid if (difference <= 0) { console.log("Contest Finished, time expired"); let expiredContest = "Contest Finished, entry time expired"; document.getElementById("expired").textContent = expiredContest; } else { // Calculate days, hours, minutes, and seconds let days = Math.floor(difference / (1000 * 60 * 60 * 24)); let hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)); let seconds = Math.floor((difference % (1000 * 60)) / 1000); // Update HTML elements with the calculated values document.getElementById("daysleft").textContent = days; document.getElementById("hoursleft").textContent = hours; document.getElementById("minutesleft").textContent = minutes; document.getElementById("secondsleft").textContent = seconds; // Schedule the next update after 1 second setTimeout(updateCountdown, 1000); } } // Call the updateCountdown function to start the countdown updateCountdown(); With these changes, your countdown timer should update every second, displaying the correct values for days, hours, minutes, and seconds until the contest ends. Let me know if you have any questions or encounter any issues! Best Regard Danish Hafeez | QA Assistant ICTInnovations Quote Link to comment https://forums.phpfreaks.com/topic/320422-pulling-values-from-scriptjs/#findComment-1623618 Share on other sites More sharing options...
Strider64 Posted May 10 Share Posted May 10 Here's a countdown clock that I did years ago, but I recently updated it a couple of months ago. countdown.js file "use strict"; /** * Calculates the time remaining until a specified end time. * @param {string} endtime - The end time in a format parseable by Date.parse. * @returns {object} An object containing the total milliseconds and the breakdown in days, hours, minutes, and seconds. */ const getTimeRemaining = (endtime) => { const total = Date.parse(endtime) - Date.now(); // Calculate the difference in milliseconds from now to the end time return { total, days: Math.floor(total / (1000 * 60 * 60 * 24)), // Convert milliseconds to days hours: Math.floor((total / (1000 * 60 * 60)) % 24), // Convert milliseconds to hours, modulo 24 minutes: Math.floor((total / 1000 / 60) % 60), // Convert milliseconds to minutes, modulo 60 seconds: Math.floor((total / 1000) % 60) // Convert milliseconds to seconds, modulo 60 }; }; /** * Initializes a countdown clock on the webpage. * @param {string} id - The ID suffix of the countdown clock container. * @param {Date} endtime - The countdown end time. */ const initializeClock = (id, endtime) => { const clock = document.getElementById(`display_clock${id}`); // Access the clock element by ID if (!clock) { console.error(`Clock with id 'display_clock${id}' not found.`); return; // Exit if no element is found } // Map each time unit to its corresponding DOM element within the clock container const fields = ['days', 'hours', 'minutes', 'seconds'].map(field => clock.querySelector(`.${field}`) ); if (fields.some(element => element === null)) { // Check if any elements are missing console.error('One or more clock elements not found:', fields); return; // Exit if missing elements are found } // Updates the countdown clock display every second const updateClock = () => { const { total, days, hours, minutes, seconds } = getTimeRemaining(endtime); // Update each field in the DOM with the new time [days, hours, minutes, seconds].forEach((val, i) => { fields[i].textContent = String(val).padStart(2, '0'); // Format with leading zeros }); if (total <= 0) { clock.textContent = "Contest Finished, entry time expired"; clearInterval(timeInterval); // Stop the timer if the countdown is complete } }; updateClock(); const timeInterval = setInterval(updateClock, 1000); // Set the timer to update every second }; /** * Fetches the countdown data and initializes the clock using that data. */ const fetchRoutine = () => { fetch('data.json') // Fetch the countdown data from a local JSON file .then(response => response.json()) .then(data => { document.getElementById("countdown_date").textContent = data.date_format; // Set the formatted date document.getElementById("display_title").textContent = data.title; // Set the event title initializeClock(1, new Date(Date.parse(data.time_left))); // Initialize the clock with the fetched data }) .catch(error => { console.error('Fetch error:', error); // Log any errors during fetch }); }; // Ensure all DOM content is loaded before executing the fetch routine. document.addEventListener('DOMContentLoaded', fetchRoutine); it pulls in data from data.json file { "time_left": "2024-08-27T11:59:59-04:00", "date_format": "Tuesday - August 28, 2024", "title": "Countdown to " } here is the HTML file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Countdown Clock</title> <link rel="stylesheet" href="reset.css"> <link rel="stylesheet" href="countdown.css"> </head> <body> <div class="info"> <h1 id="display_title"></h1> <h2 id="countdown_date"></h2> </div> <div id="display_clock1"> <figure class="box"> <div class="days"></div> <figcaption>Days</figcaption> </figure> <figure class="box"> <div class="hours"></div> <figcaption>Hours</figcaption> </figure> <figure class="box"> <div class="minutes"></div> <figcaption>Minutes</figcaption> </figure> <figure class="box"> <div class="seconds"></div> <figcaption>Seconds</figcaption> </figure> </div> <script src="countdown.js"></script> </body> </html> and even the css file countdown.css *{ -webkit-box-sizing: border-box; box-sizing: border-box; } div.info { display: block; width: 100%; max-width: 300px; height: auto; text-align: center; padding: 2px; margin: 10px auto; } div.info::after { content: ''; display: block; clear: both; } h1 { font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif; font-size: 1.2em; line-height: 1.5; } h2 { font-family: Arial, Helvetica, sans-serif; font-size: 1.0em; font-style: italic; font-weight: 300; } div#display_clock1 { display: block; width: 100%; max-width: 190px; height: auto; margin: 5px auto; background-color: pink; } div#display_clock1 figure.box { float: left; display: block; width: 100%; max-width: 40px; height: 70px; color: #fff; text-align: center; padding: 0; margin-left: 5px; } div#display_clock1 figure.box div { background-color: #2e2e2e; height: 50px; line-height: 50px; } div#display_clock1 figure.box figcaption { font-family: Arial, Helvetica, sans-serif; font-size: 0.6em; line-height: 20px; font-weight: bold; color: #000; } It's a simple countdown clock, but can be modify to enhance. I did check it out that it still runs properly. Fetching the clock can be modify to add even more countdown counters by the `id` in this example there is only 1. Quote Link to comment https://forums.phpfreaks.com/topic/320422-pulling-values-from-scriptjs/#findComment-1623653 Share on other sites More sharing options...
Danishhafeez Posted May 10 Share Posted May 10 Modify the HTML: Add additional countdown containers with unique IDs. Modify the JavaScript: Update the initializeClock function to accept a unique id for each countdown. Update the fetchRoutine function to fetch data for multiple countdowns and initialize clocks accordingly. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Countdown Clock</title> <link rel="stylesheet" href="reset.css"> <link rel="stylesheet" href="countdown.css"> </head> <body> <div class="info"> <h1 id="display_title"></h1> <h2 id="countdown_date"></h2> </div> <div id="countdown_container1" class="countdown-container"> <div id="display_clock1"> <figure class="box"> <div class="days"></div> <figcaption>Days</figcaption> </figure> <figure class="box"> <div class="hours"></div> <figcaption>Hours</figcaption> </figure> <figure class="box"> <div class="minutes"></div> <figcaption>Minutes</figcaption> </figure> <figure class="box"> <div class="seconds"></div> <figcaption>Seconds</figcaption> </figure> </div> </div> <div id="countdown_container2" class="countdown-container"> <!-- Another countdown container can be added here --> </div> <script src="countdown.js"></script> </body> </html> In the JavaScript (countdown.js), you would modify the functions accordingly: const initializeClock = (containerId, clockId, endtime) => { const clock = document.getElementById(clockId); if (!clock) { console.error(`Clock with id '${clockId}' not found.`); return; } const fields = ['days', 'hours', 'minutes', 'seconds'].map(field => clock.querySelector(`.${field}`) ); if (fields.some(element => element === null)) { console.error('One or more clock elements not found:', fields); return; } const updateClock = () => { const { total, days, hours, minutes, seconds } = getTimeRemaining(endtime); [days, hours, minutes, seconds].forEach((val, i) => { fields[i].textContent = String(val).padStart(2, '0'); }); if (total <= 0) { clock.textContent = "Contest Finished, entry time expired"; clearInterval(timeInterval); } }; updateClock(); const timeInterval = setInterval(updateClock, 1000); }; const fetchRoutine = () => { fetch('data.json') .then(response => response.json()) .then(data => { document.getElementById("countdown_date").textContent = data.date_format; document.getElementById("display_title").textContent = data.title; initializeClock("countdown_container1", "display_clock1", new Date(Date.parse(data.time_left))); // Initialize additional countdowns here if needed }) .catch(error => { console.error('Fetch error:', error); }); }; document.addEventListener('DOMContentLoaded', fetchRoutine); With these modifications, you can add multiple countdown containers to your HTML, and the JavaScript will handle initializing countdowns for each container separately based on the fetched data. Best Regard danish Hafeez | QA Assistant https://www.ictinnovations.com https://www.ictbroadcast.com Quote Link to comment https://forums.phpfreaks.com/topic/320422-pulling-values-from-scriptjs/#findComment-1623671 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.