Javascript document.getElementsByClassName is not worikng in my script [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 5 years ago.
I am working on a project which uses this script. This script takes present time and subtract it from given time.. like I gave 9 10,2017.It gives output like 29d 23h 3m 2s as remaining time
<!DOCTYPE html>
<html>
<head>
<title>Script</title>
</head>
<body>
<script type='text/javascript'>
// Set the date we're counting down to
var countDownDate = new Date('9 10,2017 00:00:00').getTime(); //m d, y h m s
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id='time'
document.getElementById('rtime').innerHTML = days + 'd ' + hours + 'h '
+ minutes + 'm' + seconds + 's';
// If the count down is over, write some text
if (distance <= 0) {
clearInterval(x);
document.getElementById('rtime').innerHTML = 'EXPIRED'; // SUBMIT FORM;
}
}, 1000); </script>
<h4 id='rtime'></h4>
<h4 id='rtime'></h4>
<h4 id='rtime'></h4>
</body>
</html>
I wanted it to give the output in all tags where I used its id. But it only gives output in the first id element. I googled the problem and found
There should be class instead of id to use it again also class should be in array
I modified the script into like this
<!DOCTYPE html>
<html>
<head>
<title>Script</title>
</head>
<body>
<script type='text/javascript'>
// Set the date we're counting down to
var countDownDate = new Date('9 10,2017 00:00:00').getTime(); //m d, y h m s
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id='time'
for(var y=0;y<=3;y++){
document.getElementsByClassName('rtime').innerHTML[y] = days + 'd ' + hours + 'h '
+ minutes + 'm' + seconds + 's';
};
// If the count down is over, write some text
if (distance <= 0) {
clearInterval(x);
document.getElementsByClassName('rtime').innerHTML[0] = 'EXPIRED'; // SUBMIT FORM;
}
}, 1000); </script>
<h4 class='rtime'></h4>
<h4 class='rtime'></h4>
<h4 class='rtime'></h4>
</body>
</html>
But its still not working.

// Set the date we're counting down to
var countDownDate = new Date('9 10,2017 00:00:00').getTime(); //m d, y h m s
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id='time'
for (var y = 0; y < 3; y++) {
document.getElementsByClassName('rtime')[y].innerHTML = days + 'd ' + hours + 'h ' +
minutes + 'm' + seconds + 's';
};
// If the count down is over, write some text
if (distance <= 0) {
clearInterval(x);
document.getElementsByClassName('rtime')[0].innerHTML = 'EXPIRED'; // SUBMIT FORM;
}
}, 1000);
<h4 class='rtime'></h4>
<h4 class='rtime'></h4>
<h4 class='rtime'></h4>
getElementsByClassName returns array of elements with given class name.
In your case do like this getElementsByClassName('rtime')[y].innerHTML and this getElementsByClassName('rtime')[0].innerHTML

Related

Countdown timer - Hide variables as they expire

looking for help with a countdown timer I have to reveal a container the page at a specific time. I'd like the "days" "hours" "minutes" to disappear when they reach zero.
Can anyone help?
<h3 id="demo"></h3>
<script>
// Set the date we're counting down to
var countDownDate = new Date("1/21/2022 11:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + " day " + hours + " hours " + minutes + " min " + seconds + " sec ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "Reserve Tickets";
}
}, 1000);
</script>
Update variables only if distance > 0
<h3 id="demo"></h3>
<script>
// Set the date we're counting down to
var countDownDate = new Date("1/21/2022 11:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
let now = new Date().getTime();
// Find the distance between now and the count down date
let distance = countDownDate - now;
// If the count down is over, write some text
if (distance >= 0) {
// Time calculations for days, hours, minutes and seconds
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + " day " + hours + " hours " + minutes + " min " + seconds + " sec ";
} else {
clearInterval(x);
document.getElementById("demo").innerHTML = "Reserve Tickets";
}
}, 1000);
</script>

JavaScript and content change after load - countdown timer from date

I'm trying to have a simple countdown timer that converts a time given on a page to a countdown.
It works, but my current issue is how the normal date is shown and then later it's parsed by the JavaScript. I want it parsed by JS right away so a user doesn't see it flicking between the date and the countdown timer.
It converts this to the countdown:
<span class="countdown">12/10/20 13:10:00</span>
This is the code:
if ($('.countdown').length)
{
$.each( $('.countdown'), function( key, value )
{
var time_listed = $(value).text();
var countdown_object = $(value);
// Set the date we're counting down to
var countDownDate = new Date(time_listed).getTime();
// Update the count down every 1 second
var x = setInterval(function()
{
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
countdown_object.text (days + " days " + hours + "h "
+ minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0)
{
clearInterval(x);
countdown_object.text("EXPIRED");
}
}, 1000);
});
}
What I am asking for, is suggestions on how to get around this problem. Is the only way to have it loaded before the HTML or what? I'm confused on the best practices for this. Everywhere keeps telling me to defer JavaScript loading...but what about stuff like this that changes the content?
In cases like this, is it a good idea to have a "core" file for content-changing stuff that loads right away, then the rest after the content or what?
The problems comes from setInterval not executing automatically , which is normal. Here's a work around it:
if ($('.countdown').length)
{
$.each( $('.countdown'), function( key, value )
{
var time_listed = $(value).text();
var countdown_object = $(value);
// Set the date we're counting down to
var countDownDate = new Date(time_listed).getTime();
var counterFunction = function()
{
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
countdown_object.text (days + " days " + hours + "h "
+ minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0)
{
clearInterval(x);
countdown_object.text("EXPIRED");
}
return counterFunction;
}
// Update the count down every 1 second
var x = setInterval(counterFunction(), 1000);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="countdown">12/10/20 13:10:00</span>
I suggest to put the date in data-date attr, like this:
<span data-date="12/10/20 13:10:00" class="countdown"></span>
than the script:
if ($('.countdown').length)
{
$.each( $('.countdown'), function( key, value )
{
var time_listed = $(value).attr("data-date");
var countdown_object = $(value);
// Set the date we're counting down to
var countDownDate = new Date(time_listed).getTime();
// Update the count down every 1 second
var x = setInterval(function()
{
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
countdown_object.text (days + " days " + hours + "h "
+ minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0)
{
clearInterval(x);
countdown_object.text("EXPIRED");
}
}, 1000);
});
}
https://jsfiddle.net/750o1neh/

Count Down Timer With User Input To Modify End Date

Is there a way to take this pre-existing code and make it so that instead of having the end date as a preset value. have it so that the user can select an end date using date inputs and time inputs. I there a way to do this by only Using HTML and Javascript with an onClick() function to avoid using PHP. Any help that I can get would be extremely helpful.
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
End Date <input type="datetime-local" id="endDate">
<button onclick="countdownTimeStart()">Start Timer</button>
<script>
// Set the date we're counting down to
function countdownTimeStart(){
var endDate = document.getElementById('endDate').value;
var dateObject = new Date(endDate);
var countDownDate = new Date(dateObject).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
</script>
</body>
</html>

Calculating countdown by hours \ minutes instead of seconds

I"m trying to use this countdown but it calculates the time every second.
I want to counter to count the time by minutes or even hours, not every second because i only display days and hours.
I've tryied to remove the var seconds or minutes but the inspect elemnts showing me a purplr blink on the timer every 1 second meaning it's still calculating the time by seconds.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top:0px;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("April 24, 2018 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</body>
</html>
Change
// Update the count down every 1 second
var x = setInterval(function() {
...
}, 1000);
to
// Update the count down every 1 minute
var x = setInterval(function() {
...
}, 1000*60);
or
// Update the count down every 1 hour
var x = setInterval(function() {
...
}, 1000*60*60);
Edit
That will update your timer every minute/hour. Now, to start countdown and update every minute/hour:
calculateCountdown();
// Update the count down every 1 minute
var x = setInterval(function() {
calculateDountdown();
}, 1000*60);
or just
calculateCountdown();
setInterval(calculateCountdown, 1000*60);
where
function calculateCountdown() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}
Check this answer to see how to refactor setInterval based solution to setTimeout based.

JavaScript timer not working on multiple instance

Below is a result of a loop and I want to run timer to count up to the set time for each of the loop result.
<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>
<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>
<span id="time" data-time="{{ $user->created_at->addHours(config('app.timer')) }}" data-url="{{ url('/TimePay/'.$user->id)}}"></span>
The timer script:
$(document).ready(function(){
$('[data-time]').each(function() {
console.log($(this))
var $this = $(this),
finalTime = $(this).data('time'),
url = $(this).data('url')
// Set the date we're counting down to
var countDownDate = new Date(finalTime).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in an element with id="demo"
document.getElementById("time").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("time").innerHTML = "EXPIRED";
}
}, 1000);
})
})
So am using Laravel and jQuery to run the timer.
I want assistance with the code because it is not working.
The trick is to "save" you intervals in an array.
If you do not do it, it gets overwritten on each loop iteration.
Then, to refer to the right span element, you have to get the iteration index for later use in an .eq() method.
You can't use an id in a loop, since it has to be unique.
Have a look at comments within the code.
$(document).ready(function(){
// an arrary to store the intervals created.
var timerArray = [];
$('[data-time]').each(function(index) {
console.log($(this).data("time"));
var finalTime = $(this).data('time');
// Set the date we're counting down to
var countDownDate = new Date(finalTime).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// this Index will be used to refer to the right span.
var thisIndex = index;
console.log("interval "+thisIndex);
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Leading zeros...
if(hours<10){hours="0"+hours}
if(minutes<10){minutes="0"+minutes}
if(seconds<10){seconds="0"+seconds}
// Display the result in an element with id="demo"
$('[data-time]').eq(thisIndex).html( days + "d " + hours + "h " + minutes + "m " + seconds + "s " );
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(timerArray[thisIndex]);
$('[data-time]').eq(thisIndex).html("EXPIRED");
}
}, 1000);
// Place this timer in an array... So it won't be overwritten.
timerArray.push(x);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-time="07/08/2017 12:30:00"></span><br>
<br>
<span data-time="07/10/2017 19:50:30"></span><br>
<br>
<span data-time="07/12/2017 5:24:24"></span><br>
<br>
Run the snippet in "full page" or look at this CodePen.

Categories