Javascript timer How to replace digits with images? - javascript

Hello how can I replace digits in following javascript timer with respective images. ie 0 with dig1.png, 1 with dig2.png, 3 with dig3. png.....colon(:) with colo.png.
00:23:01 ==>>
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
doSubmit();
document.getElementById("timeisup").innerHTML = "Time is up response.";
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
Timer.innerHTML = TotalSeconds;
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":"
+ LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : + Time;
}
And here is the html markup that shows the timer...
<span id="timer"style="font-weight: bold;"></span><script
type="text/javascript">window.onload = CreateTimer("timer", 7200);</script>
Thanks

I think the best approach is to create the images first and leave them in place
<img id="d0" src="dig0.png">
<img id="d1" src="dig0.png">
<img src="col.png">
<img id="d2" src="dig0.png">
<img id="d3" src="dig0.png">
<img src="col.png">
<img id="d4" src="dig0.png">
<img id="d5" src="dig0.png">
and then just update image src from javascript:
var digits = [document.getElementById("d0"),
document.getElementById("d1"),
document.getElementById("d2"),
document.getElementById("d3"),
document.getElementById("d4"),
document.getElementById("d5")];
function setTime(hh, mm, ss) {
digits[0].src = "dig" + Math.floor(hh / 10) + ".png";
digits[1].src = "dig" + (hh % 10) + ".png";
digits[2].src = "dig" + Math.floor(mm / 10) + ".png";
digits[3].src = "dig" + (mm % 10) + ".png";
digits[4].src = "dig" + Math.floor(ss / 10) + ".png";
digits[5].src = "dig" + (ss % 10) + ".png";
}

Old fashion and not Optimal:
First, create the HTML DOM objects:
var image = document.createElement("img");
image.className = "style here";
//image.style can come here ...
image.src = "Path/to/image/here";
Or pre-populate image with
<image src="path/to/image" id="imageId like ie0">
And Append them to the div you want in your Tick function:
var parentDiv = document.getElementById("parent div ID");
parentDiv.appendChild(image);
Modern way of doing it:
Include CSS in your code. You can add pretty styles and no worries for the images as it will be slow and somewhat inconsistent. See a live example with open source code is here: Minimal Digital Clock with CSS

Related

Online Quiz: how can I avoid timer getting refreshed when user click on refresh button in the browser toolbar/Status Bar?

htmlTable.Append("<script> var seconds = " + ttime + "; function secondPassed() { var minutes = Math.round((seconds - 30) / 60); var remainingSeconds = seconds % 60; if (remainingSeconds < 10) { remainingSeconds = '0' + remainingSeconds; } document.getElementById('countdown').innerHTML = 'Time Left :- ' + minutes + ':' + remainingSeconds; if (seconds == 0) { clearInterval(countdownTimer);document.getElementById('Button1').click(); } else { seconds--; } } var countdownTimer = setInterval('secondPassed()', 1000);</script>");
PlaceHolder1.Controls.Add(new Literal { Text = htmlTable.ToString() });
The above code is used to create a timer in .aspx.cs file. It's an online exam application.

javascript with improper initiation

As my homework I have to prepare an asp webpage for database frontpage. To gain some extra points we can add a javascript. I deceided to add a clock I've found somewhere in script tutorials and modified it a little, but my skills are not enough to place it correctly
I want to place it in my MasterPage, but whole page dissapears only the clock lefts if I add it like this:
<div id="Zawartosc" onload="showTheTime();">
<%-- clock --%>
<script src="Script.js"></script>
</div>
and here is the clock script:
function showTheTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var ampm = "am";
var colon = '<IMG SRC="clock/colon.gif">';
if (hours < 10) hours = "0" + hours;
else hours = hours + '';
if (minutes < 10) minutes = "0" + minutes;
else minutes = minutes + '';
if (seconds < 10) seconds = "0" + seconds;
else seconds = seconds + '';
document.write('<IMG SRC="clock/' + hours.charAt(0) + '.gif">');
document.write('<IMG SRC="clock/' + hours.charAt(1) + '.gif">');
document.write(colon);
document.write('<IMG SRC="clock/' + minutes.charAt(0) + '.gif">');
document.write('<IMG SRC="clock/' + minutes.charAt(1) + '.gif">');
document.write(colon);
document.write('<IMG SRC="clock/' + seconds.charAt(0) + '.gif">');
document.write('<IMG SRC="clock/' + seconds.charAt(1) + '.gif">');
}
setTimeout("showTheTime()", 1000);
showTheTime();
could you please lead or help me to correct code and make the clock appear correctly with my page?
From w3schools.com
The write() method is mostly used for testing: If it is used after an
HTML document is fully loaded, it will delete all existing HTML.
Give this a try:
<div id="Zawartosc" onload="showTheTime();">
<script src="Script.js"></script>
</div>
function createElementImg(source) {
var img = document.createElement('img');
img.src = source;
return img;
}
function showTheTime() {
var clockEle = document.getElementById("Zawartosc");
while (clockEle.hasChildNodes()) {
clockEle.removeChild(clockEle.lastChild);
}
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var ampm = "am";
var colon = "clock/colon.gif";
if (hours < 10) hours = "0" + hours;
else hours = hours + '';
if (minutes < 10) minutes = "0" + minutes;
else minutes = minutes + '';
if (seconds < 10) seconds = "0" + seconds;
else seconds = seconds + '';
clockEle.appendChild(createElementImg("clock/' + hours.charAt(0) + '.gif"));
clockEle.appendChild(createElementImg("clock/' + hours.charAt(1) + '.gif"));
clockEle.appendChild(createElementImg(colon));
clockEle.appendChild(createElementImg("clock/' + minutes.charAt(0) + '.gif"));
clockEle.appendChild(createElementImg("clock/' + minutes.charAt(1) + '.gif"));
clockEle.appendChild(createElementImg(colon));
clockEle.appendChild(createElementImg("clock/' + seconds.charAt(0) + '.gif"));
clockEle.appendChild(createElementImg("clock/' + seconds.charAt(1) + '.gif"));
}
setTimeout("showTheTime()", 1000);
showTheTime();

Javasacript Countdown timer in Days, Hours, Minute, Seconds

I'm trying to create a time-based count down clock. It is not based upon current_dates. The initial time that will be pulled will be from a separate php file. This will be for a browser based-game. When someone clicks the button to initiate this script. it will check if certain requirements are met and if so then this script will initiate. Based upon the level of the object it will pull the initial timer for that proceeding level. Hope that makes sense. Anyhow I based the timer script off of the first code I provide.
This script only accounts for minutes and seconds. I modified it to include days and hours as well. Somewhere in the process I have messed up and the script doesn't even work at all. I'm also not quite sure if this would be the best method to calculate this. So, if you have a cleaner method at doing this please share. Thank you in advance.
This script is based off of a minutes / seconds script I saw. Here's the original source:
<span id="countdown" class="timer"></span>
<script>
var seconds = 60;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
Here is the modified script that I am trying to include days, hours, minutes and seconds.
<span id="countdown"></span>
<script>
var current_level = 93578;
function timer() {
var days = Math.round(current_level/86400);
var remainingDays = Math.round(current_level - (days * 86400));
if (days <= 0){
days = current_level;
}
var hours = Math.round(remainingDays/3600);
var remainingHours = Math.round(remainingDays - (hours * 3600));
if (hours >= 24){
hours = 23;
}
var minutes = Math.round(remainingHours/60);
var remainingMinutes = Math.round(remainingHours - (minutes * 60));
if (minutes >= 60) {
minutes = 59;
}
var seconds = Math.round(remainingMinutes/60);
document.getElementById('countdown').innerHTML = days + ":" + hours ":" + minutes + ":" + seconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
I finally got back to looking at this and re-wrote the code and this works like a charm.
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
<span id="countdown" class="timer"></span>
Personally I would use the jquery countdown timer integration. It is simple and having number of options to display in different formats. Since I am fairly new to JS as well, this was the easiest way I found to get a count/timer.
http://keith-wood.name/countdown.html
Here is my worked out and tested example, based on your code
<span id="countdown"></span>
<script>
var current_level = 3002;
function timer() {
var days = Math.floor(current_level/86400);
var remainingDays = current_level - (days * 86400);
//if (days <= 0){
// days = current_level;
//}
var hours = Math.floor(remainingDays/3600);
var remainingHours = remainingDays - (hours * 3600);
//if (hours >= 24){
// hours = 23;
//}
var minutes = Math.floor(remainingHours/60);
var remainingMinutes = remainingHours - (minutes * 60);
//if (minutes >= 60) {
// minutes = 59;
//}
var seconds = remainingMinutes;
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + seconds;
//if (seconds == 0) {
// clearInterval(countdownTimer);
// document.getElementById('countdown').innerHTML = "Completed";
//}
current_level--;
}
var countdownTimer = setInterval(timer, 1000);
</script>
This code will help you deal with the issue of handling multiple timer on the single page
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');
var total_timers = seconds_inputs.length;
for ( var i = 0; i < total_timers; i++){
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var cal_seconds = seconds_inputs[i].getAttribute('value');
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
}
function timer() {
for ( var i = 0; i < total_timers; i++) {
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);
if (eval('seconds_'+ seconds_prod_id) == 0) {
clearInterval(countdownTimer);
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
} else {
var value = eval('seconds_'+seconds_prod_id);
value--;
eval('seconds_' + seconds_prod_id + '= ' + value + ';');
}
}
}
var countdownTimer = setInterval('timer()', 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
<div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>
</div>
const Panel = ({ label, n }) => (
<div className="panel">
<small>{label}</small>
<span>{n < 10 ? '0' + n : n}</span>
</div>
)
const App = () => {
const [secondsLeft, setSecondsLeft] = React.useState(86403)
React.useEffect(() => {
const interval = setInterval(() => {
if (secondsLeft == 0) {
clearInterval(interval)
console.log('Times up!')
} else {
setSecondsLeft(secondsLeft - 1)
}
}, 1000)
return () => clearInterval(interval)
})
const days = Math.floor(secondsLeft / 24 / 60 / 60)
const hoursLeft = Math.floor(secondsLeft - days * 86400)
const hours = Math.floor(hoursLeft / 3600)
const minutesLeft = Math.floor(hoursLeft - hours * 3600)
const minutes = Math.floor(minutesLeft / 60)
const seconds = secondsLeft % 60
return (
<div className="root">
<Panel label="Days" n={days} />
<Panel label="Hours" n={hours} />
<Panel label="Minutes" n={minutes} />
<Panel label="Seconds" n={seconds} />
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
.root {
display: flex;
}
.panel {
display: flex;
flex-direction: column;
align-items: center;
margin-right: 8px;
color: #444;
}
.panel small {
font-size: 9px;
text-transform: uppercase;
font-family: sans-serif;
}
.panel span {
font-size: 3em;
font-weight: bold;
font-family: serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
<span id="countdown" class="timer"></span>

Subtract to function times

I currently have two functions that capture the current dates minute in which a user loads and leaves a page.
Is there a way to combine these functions so that I can get the difference?
Ex. User loads the page at 30, and leaves at 45
Therefore, 45-30 = 15 minutes
Also is there any reason why my unload alert does not work on safari?
JAVASCRIPT
<script type="text/javascript">
window.onload = function () {
var currentdate = new Date();
var hour = currentdate.getHours();
var minutes = currentdate.getMinutes();
var seconds = currentdate.getSeconds();
alert("starts at " + minutes + " minutes");
}
window.onbeforeunload = function (e) {
var currentdate = new Date();
var hour = currentdate.getHours();
var minutes = currentdate.getMinutes();
var seconds = currentdate.getSeconds();
return ("leaves at " + minutes + " minutes");
}
</script>
Something like this ?
var pageLoadTime;
window.addEventListener("load", function () {
pageLoadTime = (new Date()).getTime();
});
window.addEventListener("beforeunload", function (e) {
var pageUnloadTime = (new Date()).getTime();
var secondsPassed = Math.round((pageUnloadTime - pageLoadTime) / 1000);
var hoursPassed = Math.floor(secondsPassed / 3600);
secondsPassed = secondsPassed % 3600;
var minutesPassed = Math.floor(secondsPassed / 60);
secondsPassed = secondsPassed % 60;
alert(hoursPassed + " hour(s), " + minutesPassed + " minute(s), " + secondsPassed + " second(s)");
});

Increase a series each time a function is called

I have divs displayed with a PHP script using foreach. Each div should call a JavaScript function and generate a new div unic with id but I don't know how to increment the series. I need a incrementing loop each time the a div calls the function. Is that possible?
This is the .php file:
<body>
<script type="text/javascript">
foreach($objects as $key => $ar1)
{
countdown_clock_abs(<?php echo $ar1['timespamSale']; ?>,1);
}
</script>
</body>
</html>
This is the JavaScript:
function countdown_clock_abs(time, format)
{
// I expected the foreach loop do the job but the php it is loaded before the javascrip is launched. So clearly this is not the way to do it.
html_code = '<div id="countdown<?php echo ar1['id']; ?>"></div>';
document.write(html_code);
countdown_abs(time, format);
}
function countdown_abs(time, format)
{
var d=new Date();
var Target_Time = (time);
var Now_time = ((d.getTime()));
Time_Left = Math.round(Target_Time-(Now_time)/1000);
if(Time_Left < 0)
Time_Left = 0;
var innerHTML = '';
switch(format)
{
case 0:
innerHTML = Time_Left + ' seconds';
break;
case 1:
days = Math.floor(Time_Left / (60 * 60 * 24));
Time_Left %= (60 * 60 * 24);
hours = Math.floor(Time_Left / (60 * 60));
Time_Left %= (60 * 60);
minutes = Math.floor(Time_Left / 60);
Time_Left %= 60;
seconds = Time_Left;
dps = 's'; hps = 's'; mps = 's'; sps = 's';
if(days == 1) dps ='';
if(hours == 1) hps ='';
if(minutes == 1) mps ='';
if(seconds == 1) sps ='';
innerHTML = days + ' day' + dps + ' ';
innerHTML += hours + ' hour' + hps + ' ';
innerHTML += minutes + ' minute' + mps + ' and ';
innerHTML += seconds + ' second' + sps;
break;
default: innerHTML = Time_Left + ' seconds';
}
document.getElementById('countdown<?php echo ar1['id']; ?>').innerHTML = innerHTML;
setTimeout('countdown_abs(' + time + ',' + format + ');', 50);
}
Modify the signature of your method to match function countdown_clock_abs(time, format, id). Now in your first block of code, you can pass the counter to the id param

Categories

Resources