Running the same javascript for multiply onclicks - javascript

Basically I want to create a directory of links, each time the link gets clicked it restarts that links timer.
<Script> function countdown(elementName, minutes, seconds) {
var element, endTime, hours, mins, msLeft, time;
function twoDigits(n) {
return (n <= 9 ? "0" + n : n);
}
function updateTimer() {
msLeft = endTime - (+new Date);
if (msLeft < 1000) {
element.innerHTML = "countdown's over!";
} else {
time = new Date(msLeft);
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours + ':' + twoDigits(mins) : mins) + ':' + twoDigits(time.getUTCSeconds());
setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
}
}
element = document.getElementById(elementName);
endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
updateTimer();
}
</script>
<p>
<a onclick='countdown("countdown",
120,0);' href="https://www.bing.com/" target="_blank">Bing</a>
<div id="countdown"></div>
</p>
<p>
<a onclick='countdown("countdown2",
120,0);' href="https://www.google.com.au/" target="_blank">Google</a>
<div id="countdown"></div>
</p>
The problem that I have is that this will only run one countdown.
Is there a simply way that each link has it's own timer without having a script for each one?

Use different div id's for countdown.
<a onclick='countdown("countdown1",
120,0);' href="https://www.bing.com/" target="_blank">Bing</a>
<div id="countdown1"></div>
</p>
<p>
<a onclick='countdown("countdown2",
120,0);' href="https://www.google.com.au/" target="_blank">Google</a>
<div id="countdown2"></div>
</p>

Related

Countdown timer goes into negative numbers instead of replacing html

I made this countdown timer to show a video after it reaches the end. However it just goes into negative numbers. Seems to be related to the part of the code to hide the content after expiry date. Here is a JS fiddle
<div id="countdown"></div>
<div id="playsession"></div>
<script>
var releaseDate = new Date('05/29/2021 9:00 UTC+1');
var expiryDate = new Date('10/11/2021 01:00AM UTC+1');
var cdNotice = 'This session will appear automatically when the countdown finishes';
var trDay = ' Days';
var trHours = ' Hours';
var trMin = ' Minutes';
var trSec = ' Seconds';
var media = "<div class=\"wistia_responsive_padding\" style=\"padding:56.25% 0 0 0;position:relative;\"><div class=\"wistia_responsive_wrapper\" style=\"height:100%;left:0;position:absolute;top:0;width:100%;\"><iframe src=\"https:\/\/fast.wistia.net\/embed\/iframe\/eiwj630vxa?videoFoam=true\" title=\"June 19 & 20 ~ Refresh & Revive ~ Gen Rabten ~ 1 Video\" allow=\"autoplay; fullscreen\" allowtransparency=\"true\" frameborder=\"0\" scrolling=\"no\" class=\"wistia_embed\" name=\"wistia_embed\" allowfullscreen msallowfullscreen width=\"100%\" height=\"100%\"><\/iframe><\/div><\/div>\r\n<script src=\"https:\/\/fast.wistia.net\/assets\/external\/E-v1.js\" async><\/script>";
</script>
Above I set the start time and expiry time.
If the person loads the page before the countdown ends it should show the countdown. If the person loads after the countdown it will show the video.
If the person loads the page after the expiry time it should show the expired message.
Timer
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 = releaseDate - now;
var gone = expiryDate - now;
if (distance < 0 && gone > 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = "";
document.getElementById('playsession').innerHTML = media;
return;
}
if (gone < 0) {
clearInterval(timer);
document.getElementById('playsession').innerHTML = '<p>This video has now expired</p>';
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('countdown').innerHTML = '<p>' + cdNotice + '</p>';
document.getElementById('countdown').innerHTML += '<p>';
if (days > 0) {
document.getElementById('countdown').innerHTML += '<b>' + days + trDay + '</b> ';
}
if (hours > 0) {
document.getElementById('countdown').innerHTML += '<b>' + hours + trHours + '</b> ';
}
if (minutes > 0) {
document.getElementById('countdown').innerHTML += '<b>' + minutes + trMin + '</b> ';
}
document.getElementById('countdown').innerHTML += '<b>' + seconds + trSec +'</b>';
document.getElementById('countdown').innerHTML += '</p>';
}
timer = setInterval(showRemaining, 1000);
Your expire date is incorrect, add space before AM, then it will work, otherwise your condition is not met, because gone = NaN.
With this it works correctly:
var expiryDate = new Date('10/11/2021 01:00 AM UTC+1')

How to change current time with Javascript

I want to show current time on my webpage. When I push F5, I can get the time, but it's not changing. Help me..
HTML
<div id="time" class="timer">
show_time
</div>
Javascript
var text2 = document.getElementById("time");
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var dn = "PM";
if (hours<12)
dn="AM";
if (hours>12)
hours=hours-12;
if (hours==0)
hours=12;
if (minutes<=9)
minutes="0"+minutes;
if (seconds<=9)
seconds="0"+seconds;
setInterval(setTime, 1000);
function setTime(){
text2.innerHTML ="현재 시간: <br>"+ hours + ':' +
minutes + ':' + seconds+ "<bn>"+dn;
}
setTime();
Thank you!
Try this
const el = document.getElementById('nav-time');
function updateClock() {
var now = new Date();
var time = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
el.innerHTML = time;
}
setInterval(updateClock, 1);
<li><span id="nav-time">Clock
<span class="divider"> | </span>
function setTime(){
document.getElementById("time").innerHTML ="현재 시간: <br>"+ hours + ':' +
minutes + ':' + seconds+ "<bn>"+dn;
}
You have to add something to your current code so that your setTime function actually adds its output to the DOM. I used document.getElementById("time") to add the time from your function to the page.
You need to get the current time inside the function, otherwise it will return value that you got when function was called for the firs time
function setTime(){
var text2 = document.getElementById("time");
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var dn = "PM";
if (hours<12)
dn="AM";
if (hours>12)
hours=hours-12;
if (hours==0)
hours=12;
if (minutes<=9)
minutes="0"+minutes;
if (seconds<=9)
seconds="0"+seconds;
text2.innerHTML ="현재 시간: <br>"+ hours + ':' +
minutes + ':' + seconds+ "<bn>"+dn;
}
setTime();
setInterval(setTime, 1000);
https://jsfiddle.net/1gc8ymkd/

How do I make my Javascript Clock 'live'?

I would like assistance on making this clock I created in Javascript/HTML update in real-time.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script>
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
}
</script>
</head>
<body onload="timer()">
<div id="txt"></div>
<body>
<h1>Clock</h1>
</body>
</html>
Any help would be appreciated.
You should create an interval timer and just call your timer function every X milliseconds, as you are displaying millisecond precision you might want to keep this low like 100ms. I suggest using setInterval for this. Just put this in your script block:
setInterval(timer, 100);
Here is a full example:
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
}
setInterval(timer, 100);
<div id="txt"></div>
Use the setTimeout function (see window.setTimeout)
In your case:
Call the timer function and add
window.setTimeout(timer, 50);
at the very end of the function.
Example:
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
window.setTimeout(timer, 50);
}
timer();
<div id="txt"></div>

Dynamically update time without refreshing the page

<html>
<head>
<script>
function updateClock() {
var time = now.getHours() + ':' + now.getMinutes(),
document.getElementById('current').innerHTML = time;
setTimeout(updateClock, 1000);
}
</script>
</head>
<body onload="updateClock()">
<p id="current"> </p>
</body>
</html>
Above is the code for dynamically update real time, it is not showing any thing on the browser. Would really appreciate help
Thank you.
Show time using Js :
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('current').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
<body onload="startTime()">
<p id="current">Time loading..</p>
</body>
OR
Your code edited:
function updateClock() {
var now = new Date();
var time = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
document.getElementById('current').innerHTML = time;
setTimeout(updateClock, 1000);
}
<body onload="updateClock()">
<p id="current"></p>
</body>
You were missing var now = new Date(); and also now.getSeconds();.
There are some errors in updateClock:
function updateClock() {
var now = new Date()
var time = now.getHours() + ':' + now.getMinutes();
document.getElementById('current').innerHTML = time;
setTimeout(updateClock, 1000);
}
now must be a Date object.
now needed to be a date object
You had a comma instead of a semicolon after now.getMinutes(),
I recommend using
* padding
* setInterval
* window.onload instead of body onload
I added seconds to show it updates. If you only need hours and minutes, change the interval time to 10000 or so.
function pad(num) {
return String("0"+num).slice(-2);
}
function updateClock() {
var now = new Date();
var time = pad(now.getHours()) + ':' + pad(now.getMinutes()) + ":" + pad(now.getSeconds());
document.getElementById('current').innerHTML = time;
}
window.onload = function() {
setInterval(updateClock, 500); // use a shorter interval for better update
}
<p id="current"></p>

Adapting a stopwatch script to return minutes and seconds elapsed

I have found a script that counts seconds and minutes. I would like get the minutes and seconds value and store it in a variable when I clicked a stop button, how should I do it?
var initialTime = Date.now();
window.setInterval(checkTime, 100);
function checkTime( miliseconds) {
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
if(seconds > 30 || minutes > 0) {
$('#timer').html('<span style="color: red">' + minutes + ': ' + seconds + '</span>');
} else {
$('#timer').html('<span style="color: black">' + minutes + ': ' + seconds + '</span>');
}
}
function convertTime(miliseconds) {
totalSeconds = Math.floor(miliseconds/1000);
minutes = Math.floor(totalSeconds/60);
seconds = totalSeconds - minutes * 60;
return minutes,seconds;
}
Make a button and attach an event on it. Then clear the interval when the button is clicked:
$("button").on('click', function() {
window.clearInterval(interval);
});
Demo: https://jsfiddle.net/76t086c2/
You can either get the value from the div#timer or set the minutes/seconds in an input and when the button is clicked, get the value.
You can return valued from your function like this:
HTML
<button id="stop">Stop</button>
<button id="start" disabled>Start</button>
<div id="timer"></div>
<div id="output"></div>
JavaScript
var initialTime = Date.now();
var timer = window.setInterval(checkTime, 100);
function checkTime() {
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
if(formatted.seconds > 30 || formatted.minutes > 0) {
$('#timer').html('<span style="color: red">' + formatted.minutes + ': ' + formatted.seconds + '</span>');
} else {
$('#timer').html('<span style="color: black">' + formatted.minutes + ': ' + formatted.seconds + '</span>');
}
return formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return {'seconds': seconds,'minutes':minutes};
}
function toggle() {
$('#start, #stop').prop('disabled', function(i, v) { return !v; });
}
$('#stop').on('click',function() {
clearInterval(timer);
toggle();
var t = checkTime();
$('#output').html('Time was stopped at: '+t.minutes + ':' + t.seconds)
})
$('#start').on('click',function() {
initialTime = Date.now();
timer = window.setInterval(checkTime, 100);
toggle();
})
You can see it working here: https://jsfiddle.net/jqy0ehbp/3/
Ok, you have 2 dates.
get the difference in miliseconds and format the result.
var initialTime = new Date(2016, 2, 09, 10, 00, 0);
var now = new Date(Date.now());
var dateDifference = (now - initialTime);
console.log('Diff miliseconds = ', dateDifference);
console.log('Result: ', FormatMiliseconds(dateDifference));
You can view an example in this fiddle:
jsfiddle

Categories