Function not calling from body page - javascript

I have one file main.js. With 2 functions
function clockDown(scs,ids){
var countdownTimer = setInterval(function(){
$(".trf_"+ids).html(timer(scs));
scs--;
}, 1000);
}
function timer(seconds){
var seconds = seconds;
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;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
return (days + ":" + hours + ":" + minutes + ":" + remainingSeconds);
if (seconds == 0) {
return ("Completed");
} else {
seconds--;
}
}
I include this file at the bottom of the page. In middle of page I am trying call function but zero results
<li>
<script type="text/javacsript">$(document).ready(function(){ clockDown($timeLeft,$PostCoinJoinedItemsId); });</script>
</li>
What I doing wrong?
But calling a function in main.js is working well

I've tested, and it works just fine. You have a typo
type="text/javacsript"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="trf_"></div>
<li>
<script type="text/javascript">
$(document).ready(function () {
clockDown(10, '');
});
</script>
</li>
<script>
function clockDown(scs, ids) {
var countdownTimer = setInterval(function () {
$(".trf_" + ids).html(timer(scs));
scs--;
}, 1000);
}
function timer(seconds) {
var seconds = seconds;
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;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
return (days + ":" + hours + ":" + minutes + ":" + remainingSeconds);
if (seconds == 0) {
return ("Completed");
} else {
seconds--;
}
}
</script>
</body>
</html>

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>

Javascript timer How to replace digits with images?

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

when implementing javascript countdown the other html elements disappear

I made a layout and had everything set and when I implement the counter portion under my text all the other HTML elements disappear why is that? Also is there any way I can make an email alert when the counter gets to a specific time?
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-
scalable=0, width=device-width;">
<title>Welcome to Tiffany & Co.</title>
<link rel="stylesheet" href="index.css"
type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<!--Enable media queries in some unsupported subrowsers-->
<script type="text/javascript" src="css3-mediaqueries.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="wrapper">
<h1>Welcome to Store</h1>
<p>The WiFi Password is:</p>
<h2 align=center>
<font color="red">Diamonds</font>
</h2>
<p>It will change in:</p>
<p>
<script type="text/JavaScript">
window.document.onload = function () {
tick();
setInterval(tick, 1000);
};
function tick() {
var d = new Date();
var currentDate = new Date(d.getUTCFullYear(),
d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(),
d.getUTCMinutes(), d.getUTCSeconds(),
d.getUTCMilliseconds());
var endDate = new Date(currentDate.getFullYear(),
currentDate.getMonth(), currentDate.getDate() + (30
/*
saturday */
- currentDate.getDay()), 16
/* 9 AM Mountain
Time = 4 PM GMT */
);
var secondsUntilSaturday = Math.floor((endDate.getTime() - currentDate.getTime()) / 1000);
var timeUntilSaturday = secondsToTime(secondsUntilSaturday);
document.body.innerHTML = (timeUntilSaturday.h + " hours, " + timeUntilSaturday.m + " minutes, " + timeUntilSaturday.s + "
seconds");
}
function secondsToTime(secs) {
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
var obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
</script>
<div id="logo">
<img src="logo.png" width="108" height="14" alt="Tiffany & Co." />
</div>
</div>
</body>
</html>
Your HTML content disappears because of the line:
document.body.innerHTML = (timeUntilSaturday.h + " hours, " + timeUntilSaturday.m + " minutes, " + timeUntilSaturday.s + " seconds");
document.body.innerHTML will write content to the body element, replacing anything that's there. You can replace document.body.innerHTML with document.write.
To answer your second question, no JavaScript can't send email on it's own, but via AJAX it can call a script on your server to send email.
That's because you're replacing whole body content with your timer
document.body.innerHTML = (
timeUntilSaturday.h +" hours, "+
timeUntilSaturday.m +" minutes, "+ timeUntilSaturday.s +"
seconds"
);
Instead of this add <div> for timer and set content with your timer
<div id="timer"></div>
<script>
document.getElementById('timer').innerHTML = (
timeUntilSaturday.h +" hours, "+
timeUntilSaturday.m +" minutes, "+ timeUntilSaturday.s +"
seconds"
);
</script>
Since you're refrencing JQuery, I've used that for you, but really only in one spot...
This should do what you need it to do: Here's a fiddle
Also here's the code from that fiddle:
<script>
//start your interval to update your timer.
setInterval(function() {
//get ms until Saturday 9AM.
var ms = untilTimeOfWeek(6, 9, 0, 0);
$('#timer').text(getHours(ms) + ' hours ' + getMinutes(ms) + ' minutes ' + getSeconds(ms) + ' seconds');
}, 100);
//gets the time left until a specific time of week.
function untilTimeOfWeek(day, hour, min, sec) {
var currdate = new Date();
var currday = currdate.getDay();
var daydiff = (day - currdate.getDay()) * 86400000;
var hourdiff = (hour - currdate.getHours()) * 3600000;
var mindiff = (min - currdate.getMinutes()) * 60000;
var secdiff = (sec - currdate.getSeconds()) * 1000;
return daydiff + hourdiff + mindiff + secdiff;
}
//get the hours from some milliseconds.
function getHours(ms) {
return Math.floor(ms / 3600000);
}
//get the minutes from some milliseconds.
function getMinutes(ms) {
return Math.floor((ms % 3600000) / 60000);
}
//get the seconds from some milliseconds.
function getSeconds(ms) {
return Math.floor(((ms % 3600000) % 60000) / 1000);
};​
</script>
<div id="timer"></div>
NOTE: +new Date is just shorthand for converting a Date to a numeric type in JavaScript.
I hope that helps.
EDIT: Updated to get 9am the following Saturday.

Categories

Resources