when implementing javascript countdown the other html elements disappear - javascript

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.

Related

Function not calling from body page

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>

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)");
});

Why isn't my web page displaying the time (javaScript)

Hey guys in my head I have linked the java script file
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tech News</title>
<link href="layout.css" rel="stylesheet" type="text/css" />
<script type ="text/javascript" src=" script.ja"> </script>
and in the java script file I have this code
window.onload = initDate;
function initDate()
{
now = new Date();
localtime = now.toString();
globaltime = now.toGMTString();
document.write("<b> Local time: </b> " + localtime + "<br>");
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write ("<font size = '+1'>");
document.write(hours + ":" + mins +":" + secs);
document.write("</font>");
document.getElementById("time").innerHTML = dtString;
}
Now this code should display the string in thie div tag but it doesn't
document.getElementById("time").innerHTML = dtString;
Here is the div tag.
<div id="time"> <!--Time-->
</div>
My website is 100& verified with no coding errors, both HTML and CSS.
So what will be the problem?
Thanks to Patrick I realized that I did not declare dtString.
Instead of complicating things the simple solution was to copy the text in to a div tag, which I had found useful since it displayed the date and time.
<div id="date">
<script>
now = new Date();
localtime = now.toString();
globaltime = now.toGMTString();
document.write(localtime);
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write ("<font size = '+1'>");
document.write(hours + ":" + mins +":" + secs);
document.write("</font>");
</script>
</div>

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

How to display system time?

I want to display the system time on my jsp page. How can i do it? I'm trying this but only date is getting displayed that and not the time. It's all working fine in Internet Explorer but not in other browsers.
<td colspan="1" height="4" align="left" width="260" >
<font class="welcome1">
<strong>
<script language="JavaScript" src="js/date.js"></script>
<span id="clock">
<script language="JavaScript"
src="js/digitalClock.js"></script>
</span>
</strong>
</font>
</td>
Displaying the time on a web-page using js should be trivial .
new Date().toLocaleString() // displays date and time
new Date().toLocaleDateString() // displays date
new Date().toLocaleTimeString() // displays time
To display time you can use Date.
<html>
<head>
<script type="text/javascript">
<!--
function updateTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
var v = hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
v+="PM";
} else {
v+="AM"
}
setTimeout("updateTime()",1000);
document.getElementById('time').innerHTML=v;
}
updateTime();
//-->
</script>
</head>
<body>
<h4>Current Time: <span id="time" /></h4>
</body>
</html>
I've tested it in firefox and chrome. Found on this site.
Edit: time now gets updated every second.
You should read the documentation about the Date object in JavaScript (Date). It would be easier if you post the JS source.
/* set Date */
function tick() {
/* Get date in epoch */
var epoch = Date.now();
document.querySelector("#epoch").innerHTML = epoch;
/* Separate epoch */
var datetime = new Date(epoch);
var year = datetime.getFullYear();
var month = datetime.getMonth() + 1; // (0-11)
var date = datetime.getDate();
var hour = datetime.getHours();
var minute = datetime.getMinutes();
var second = datetime.getSeconds();
document.querySelector("#datetime").innerHTML =
year + "-" + addZero(month) + "-" + addZero(date) + " " +
addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);
}
// Add 0 if argument < 10
function addZero(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
/* Call tick in interval 1 second */
setInterval(tick, 1000);
<p id="epoch"></p>
<p id="datetime"></p>
This seems the easiest solution, which uses setInterval with two arguments, the first being a callback, the second the interval in ms:
setInterval(function(){
document.write(new Date().toLocaleTimeString();
},1000);
So my solution should be the accepted answer because it is a real time.
For Date You can use below Javascript. Time will display in a text box. You can modify as per your requirement.
<html>
<head>
<script type="text/javascript">
var timer = null
function stop()
{
clearTimeout(timer)
}
function start()
{
var time = new Date()
var hours = time.getHours()
var minutes = time.getMinutes()
var seconds = time.getSeconds()
var clock = hours + ":" + minutes + ":" + seconds
document.forms[0].display.value = clock
timer = setTimeout("start()",1000)
}
</script>
</head>
<body onload="start()" onunload="stop()">
<form>
<input type="text" name="display" size="20">
</form>
</body>
</html>

Categories

Resources