Multiple Raphael Clocks on one page, not passing hours/minutes - javascript

Working through a teaching example for very crisp Raphael-library world clocks and I'm missing something somewhere: Clocks display with serverHours and serverMinutes set as static values. Code below does not display. Greatly appreciate 2nd (or more) set of eyes catching what I'm missing. Thanks!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Multiple Raphael Clocks on Same Page</title>
<meta name="description" content="">
<meta name="keywords" content="">
<script type="text/javascript" src="js/raphael-min.js"></script>
<script type="text/javascript"
function updateClock()
{
var currentTime = new Date();
var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
currentHours = ( currentHours < 10 ? "0" : "" ) + currentHours;
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
</script>
<body onload="updateClock();">
<div id="clock" style="padding:0px;"></div>
<script type="text/javascript">
cities = [['Houston',-6],['Charleston',-5],['London',0],['Malta',1],['Bucharest',2],['Brisbane',10],['San Diego',-9]];
serverHours = currentHours;
serverMinutes = currentMinutes;
clock24 = false;
</script>
<script type="text/javascript">
function Clock( paper, x, y, offH, offM, title, clock24 )
{
this.paper = paper;
this.centerX = x;
this.centerY = y;
this.offsetHour = offH;
this.offsetMinute = offM;
this.title = title;
this.radius = 14;
this.circle;
this.arrowHour;
this.arrowMinute;
this.clock24 = clock24;
this.Clock = function()
{
this.circle = this.paper.circle(this.centerX, this.centerY, this.radius);
this.circle.attr({"fill": "#fff", "stroke": "#fff"});
this.arrowHour = this.paper.path(
"M" + this.centerX + " " + (this.centerY - this.radius + 6) + " "
+ "L" + this.centerX + " " + this.centerY
);
this.arrowHour.attr({"stroke": "#fff", "stroke-width": "2"});
this.arrowMinute = this.paper.path(
"M" + this.centerX + " " + (this.centerY - this.radius + 2) + " "
+ "L" + this.centerX + " " + this.centerY
);
this.arrowMinute.attr({"stroke": "#fff", "stroke-width": "2"});
var label = this.paper.text(this.centerX, (this.centerY + this.radius + 10), title);
label.attr({"fill" : "#666", "font-size" : "9"});
}
this.showTime = function()
{
var date = new Date();
var hours = date.getHours() + this.offsetHour;
if (hours > 24) hours -= 24;
if (hours < 0) hours += 24;
var dHours = hours;
var dPostfix = "";
var color = (13 - Math.ceil(13.0/144.0 * Math.pow(Math.abs(hours-12), 2))).toString(16);
var minutes = date.getMinutes() + this.offsetMinute;
this.arrowMinute.rotate(minutes*6, this.centerX, this.centerY);
if (hours > 12) hours -= 12;
if (!this.clock24)
{
dPostfix = (dHours >= 12 ? " PM" : " AM");
dHours = hours;
}
this.arrowHour.rotate((parseFloat(hours)+parseFloat(minutes)/60)*30, this.centerX, this.centerY);
if (minutes < 10) minutes = "0" + minutes;
this.circle.attr({"fill": "#"+color+color+color, "stroke": "#"+color+color+color, "title": "" + dHours+":"+minutes+dPostfix});
}
this.Clock();
}
var clock = new Array();
function refreshTime()
{
if (clock)
{
for (var i = 0; i < clock.length; i++)
{
clock[i].showTime();
}
}
}
var paper = Raphael("clock", 330, 60);
var date = new Date();
var offsetHours = serverHours - date.getHours();
var offsetMinutes = serverMinutes - date.getMinutes();
var x = 20;
var y = 21;
for (i = 0; i < cities.length; i++)
{
clock.push(new Clock(paper, x, y, offsetHours + cities[i][1], offsetMinutes, cities[i][0], clock24));
x += 55;
}
refreshTime();
setInterval( "refreshTime()", 30000 );
</script>
</body></html>

You have many errors in your JavaScript. Open your page in Google Chrome, press F12, switch to "Console" tab and see all errors marked with red color.
Also you're using #fff fill/stroke color everywhere which is white so it becomes invisible on white background.
Also you're trying to globally use variable "currentHours" etc. which definition is enclosed in function so it becomes not global but local. Move it to a global scope (above all functions).

Related

how to declare div and id/class in java script

I have the index.html file in that form fields are there form action is confirm.html. In confirm.html some data, I displayed using js. But showing the only table I decided to I use menus in that so more attractive for users. Whenever I'm trying to declare div(<h1>data</h1>) in confirm.html it won't be showing any data. so I decided to declare using js.
Top of the headers i have to show those menus:
document.write("<div class="Menu">");
document.write("<div class="leftmenu">");
document.write("<h4>Fegli</h4>");
document.write("<div class="Menu">");
doucment.write("<ul>");
document.write("<li>Home</li>");
document.write("</ul>");
document.write("</div>");
document.write("</div>");
document.write("</div>");
Confirm.html: code
<html>
<head>
<script type="text/javascript" src="calculate.js">
</script>
</head>
<body onload="init();">
<div id="Menu">
it wont showing on web page
</div>
</body>
</html>
Calculate.js code
// Called on body's `onload` event
var cumulative=0;
function init() {
var salary = parseInt(localStorage.getItem("salary"));
var percent = parseFloat(localStorage.getItem("percent"));
var age = parseInt(localStorage.getItem("age"));
var rAge = parseInt(localStorage.getItem("rAge"));
var sel = localStorage.getItem("sel");
var roundedSalary = parseInt(Math.ceil((salary + 2000) / 1000) * 1000); //Doing Rounding for basic column Display
var basic;
var factor = 0;
var biWeekly = 0, monthly = 0,annual = 0;
//Displaying Headers
document.write("<head>");
document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"confirm.css\">");
document.write("<title>Result</title>");
document.write("</head>");
document.write("<body>");
/* document.write("<center>")
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
document.write("<h1>" + "FEGLI CALCULATIONS ON" + " " + today + "</h1>");
document.write("</center>")
*/
document.write("<table><tr><th> Age </th><th> Annual-Salary </th><th> BiWeekly-Premium </th><th> Monthly-Premium </th><th> Annual-Premium </th><th> Cumulative-Premium </th><th>Basic </th><th> Total </th></tr>");
basic = parseInt(roundedSalary * calculateFactor(age));
//document.write("roundedSalary"+roundedSalary+"calculateFactor"+calculateFactor(age));
premium = calculateBiweekly(salary, basic, age, rAge);
biWeekly = premium[0];
monthly = premium[1];
annual = premium[2];
cumulative = premium[3];
document.write("<tr><td>" + age + "/" + (age + 1) + "</td><td>" + "$" + salary.toFixed(2) + "</td><td>" + "$" + biWeekly.toFixed(2) + "</td><td>" + "$" + monthly.toFixed(2) + "</td><td>" + "$" + annual.toFixed(2) + "</td><td>" + "$" + cumulative.toFixed(2) + "</td><td>" + "$" + basic + "</td><td>-</td></tr>");
salary = parseFloat(salary);
for (var i = age + 1; i < 101; i++) {
document.write("<tr>");
document.write("<td>" + i + "/" + (i + 1) + "</td>");
if (i < rAge) {
salary = salary + (salary * percent);
roundedSalary = parseInt(Math.ceil((salary + 2000) / 1000) * 1000);
// document.write("age"+i+"roundedSalary"+roundedSalary+"<br>");
document.write("<td>" + "$" + salary.toFixed(2) + "</td>");
} else {
salary = 0;
document.write("<td>-</td>");
}
basic = parseInt(roundedSalary * calculateFactor(i));
premium = calculateBiweekly(salary, basic, i);
biWeekly = premium[0];
monthly = premium[1];
annual = premium[2];
cumulative = premium[3];
document.write("<td>" + "$" + biWeekly.toFixed(2) + "</td>");
document.write("<td>" + "$" + monthly.toFixed(2) + "</td>");
document.write("<td>" + "$" + annual.toFixed(2) + "</td>");
document.write("<td>" + "$" + cumulative.toFixed(2) + "</td>");
document.write("<td>" + "$" + basic + "</td>");
document.write("<td>-</td>");
document.write("</tr>");
}
document.write("</table>");
document.write("</body>")
}
function calculateFactor(age) {
var factor = 0;
if (age > 35 && age < 45) {
switch (age) {
case 36:
factor = 1.9;
break;
case 37:
factor = 1.8;
break;
case 38:
factor = 1.7;
break;
case 39:
factor = 1.6;
break;
case 40:
factor = 1.5;
break;
case 41:
factor = 1.4;
break;
case 42:
factor = 1.3;
break;
case 43:
factor = 1.2;
break;
case 44:
factor = 1.1;
break;
}
} else if (age <= 35) {
factor = 2;
} else if (age >= 45) {
factor = 1;
}
return factor;
}
function calculateBiweekly(salary, basic, age) {
var biWeekly = 0;
if (salary > 0) {
biWeekly = ((basic / calculateFactor(age)) * 0.15) / 1000;
monthly = ((basic / calculateFactor(age)) * 0.325) / 1000;
} else if (salary == 0 && age <= 65) {
biWeekly = ((basic / calculateFactor(age)) * (2.455 / 2.166)) / 1000;
monthly = ((basic / calculateFactor(age)) * (2.455)) / 1000;
} else if (salary == 0 && age > 65) {
//document.write("age"+age+"salary"+salary+"<br>");
biWeekly = ((basic / calculateFactor(age)) * (2.13 / 2.166)) / 1000;
monthly = ((basic / calculateFactor(age)) * (2.13)) / 1000;
}
annual = 12 * monthly;
cumulative = cumulative+annual;
//document.write("cumulative"+cumulative+"<br>");
return [biWeekly, monthly, annual, cumulative];
}// Called on body's `onload` event
I don't recommend document.write() to create element in DOM.
You need to use document.createElement() function to create new element using javascript.
function addMenu() {
var html = '<div class="Menu">';
html += '<div class="leftmenu">';
html += '<h4>Fegli</h4>';
html += '<div class="Menu">';
html += '<ul><li>Home</li></ul>';
html += '</div>';
html += '</div>';
html += '</div>';
document.getElementById("Menu").innerHTML = html;
}
addMenu();
<div id="Menu"></div>
In your code you applied table using document.write(), you can also create table tag using document.createElement() function. check below examples:
Example 1 :
function addTable() {
var c, r, t;
t = document.createElement('table');
t.border=1;
r = t.insertRow(0);//create row
c = r.insertCell(0);///create cell
c.innerHTML = "Apple";
c = r.insertCell(1);///create second cell
c.innerHTML = "Orange";
document.getElementById("mainContainer").appendChild(t);
}
addTable();
<div id="mainContainer"></div>
Example 2 :
function addTable() {
var html = "<table border='1'><tr><td>Apple</td><td>Orange</td></tr></table>";
document.getElementById("mainContainer").innerHTML = html;
}
addTable();
<div id="mainContainer"></div>
Both example will give same result.

Cannot read property 'textContent' of null at renderTime

I'm trying to create a working clock with JavaScript, but the code won't run. I'm getting the following error in my console:
Cannot read property 'textContent' of null at renderTime
This is the HTML:
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-3.2.1.js" charset="utf-8"></script>
<script src="js/alarm.js" charset="utf-8"></script>
<title>Alarm Clock</title>
</head>
<body>
<div id="clockDisplay" class="clockStyle">3 : 15 : 25 AM</div>
</body>
</html>
And this is the JavaScript:
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if (h == 0) {
h = 12;
} else if (h < 12) {
h = h - 12;
diem = "PM"
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent(h + ":" + m + ":" + s + "" + diem);
setTimeout('renderTime()', 1000)
}
renderTime();
The problem here is that the script is executing before the page is loaded.
You just need to move the js/alarm.js script tag to the end of your body tag, so it executes when the page is fully loaded.
And textContent is a property and not a function so your code will raise an Exception, change the following line:
myClock.textContent ( h + ":" + m + ":" + s + "" + diem);
To:
myClock.textContent = h + ":" + m + ":" + s + "" + diem;
Demo:
I refactored your code and corrected it so it takes in consideration these changes, this is a working snippet:
function renderTime(){
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if (h == 0) {
h = 12;
} else if (h < 12) {
h = h-12;
diem = "PM"
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + ":" + s + "" + diem;
setTimeout('renderTime()', 1000)
}
renderTime();
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-3.2.1.js" charset="utf-8"></script>
<title>Alarm Clock</title>
</head>
<body>
<div id="clockDisplay" class="clockStyle">3 : 15 : 25 AM</div>
<script src="js/alarm.js" charset="utf-8"></script>
</body>
</html>
The reason you get this error is the fact that the function is called when the browser parses the script tag. By then the actual HTML body has not been parsed/rendered and the element is indeed not found in the dom.
Try:
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-3.2.1.js" charset="utf-8"></script>
<script src="js/alarm.js" charset="utf-8"></script>
<title>Alarm Clock</title>
</head>
<body onload="renderTime();">
<div id="clockDisplay" class="clockStyle">3 : 15 : 25 AM</div>
</body>
</html>
And remove the function call at then end of your script.

setInterval function is not working

I’m making a local time watch in jQuery. I wrote some piece of code but it’s not working. Here is my code:
$(document).ready(function(){
function addZero(i) {
if (i <= 9) {
i = "0" + i;
}
return i;
}
var d = setInterval(function(){
var z = new Date();
var h = addZero(z.getHours());
var m = addZero(z.getMinutes());
var s = addZero(z.getSeconds();
var a = '';
if (h > 11 ) a = "PM"
else a = "AM"
if (h == 16) h = '0'+4
$('pre').html(h + ":" + m + ":" + s + " " + "a");
},1000);
});
You made some mistakes - check code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var d,z,h,m,s,a
function addZero(i) {
if (i <= 9) i = "0" + i;
return i;
}
d = setInterval( function(){
z = new Date();
h = addZero(z.getHours());
m = addZero(z.getMinutes());
s = addZero(z.getSeconds());
a = '';
if (h > 11 ) a = "PM"
else a = "AM"
if (h == 16) h = '0'+4
$('#timer').html(h + ":" + m + ":" + s + " " + a);
},1000);
});
</script>
<pre id="timer"></pre>
You have missed one )
$(document).ready(function(){
function addZero(i) {
if (i <= 9) {
i = "0" + i;
}
return i;
}
var d = setInterval(function(){
var z = new Date();
var h = addZero(z.getHours());
var m = addZero(z.getMinutes());
var s = addZero(z.getSeconds());
var a = '';
if (h > 11 ) {
a = "PM" ;
}
else {
a = "AM";
}
if (h == 16) {
h = '0'+4;
}
$('pre').html(h + ":" + m + ":" + s + " " + a);
},1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>
Please use below code in your code there is a function var d which is declared for setInterval but I didnt see this function as a called. so from where it will call. above answer is also fine and correct but global variable declaration is not needed here for d,z,h,m,s,a in below code. Local variable is also working.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
//var d,z,h,m,s,a
function addZero(i) {
if (i <= 9) i = "0" + i;
return i;
}
setInterval( function(){
var z = new Date();
var h = addZero(z.getHours());
var m = addZero(z.getMinutes());
var s = addZero(z.getSeconds());
var a = '';
if (h > 11 ) a = "PM"
else a = "AM"
if (h == 16) h = '0'+4
$('pre').html(h + ":" + m + ":" + s + " " + a);
},1000);
});
</script>
<pre id="timer"></pre>

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();

Count up javascript

Its now showing secont counter up timer
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function CountUp(initDate,id){
this.beginDate = new Date(initDate);
this.numOfDays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
var currYear = (new Date()).getFullYear();
if ( (currYear % 4 == 0 && currYear % 100 != 0 ) || currYear % 400 == 0 ) {
this.numOfDays[1] = 29;
}
this.borrowed = 0, this.years = 0, this.months = 0, this.days = 0;
this.hours = 0, this.minutes = 0, this.seconds = 0;
this.calculate();
this.update(id);
}
CountUp.prototype.datePartDiff=function(then, now, MAX){
var temp = this.borrowed;
this.borrowed = 0;
var diff = now - then - temp;
if ( diff > -1 ) return diff;
this.borrowed = 1;
return (MAX + diff);
}
CountUp.prototype.formatTime=function(){
this.seconds = this.addLeadingZero(this.seconds);
this.minutes = this.addLeadingZero(this.minutes);
this.hours = this.addLeadingZero(this.hours);
}
CountUp.prototype.addLeadingZero=function(value){
return (value + "").length < 2 ? ("0" + value) : value;
}
CountUp.prototype.calculate=function(){
var currDate = new Date();
var prevDate = this.beginDate;
this.seconds = this.datePartDiff(prevDate.getSeconds(), currDate.getSeconds(), 60);
this.minutes = this.datePartDiff(prevDate.getMinutes(), currDate.getMinutes(), 60);
this.hours = this.datePartDiff(prevDate.getHours(), currDate.getHours(), 24);
this.days = this.datePartDiff(prevDate.getDate(), currDate.getDate(), this.numOfDays[currDate.getMonth()-1]);
this.months = this.datePartDiff(prevDate.getMonth(), currDate.getMonth(), 12);
this.years = this.datePartDiff(prevDate.getFullYear(), currDate.getFullYear(),0);
}
CountUp.prototype.update=function(id){
if ( ++this.seconds == 60 ) {
this.seconds = 0;
if ( ++this.minutes == 60 ) {
this.minutes = 0;
if ( ++this.hours == 24 ) {
this.hours = 0;
if ( ++this.days == this.numOfDays[(new Date()).getMonth()-1]){
this.days = 0;
if ( ++this.months == 12 ) {
this.months = 0;
this.years++;
}
}
}
}
}
this.formatTime();
var countainer = document.getElementById(id);
countainer.innerHTML ="<strong>" + this.years + "</strong> <small>years</small> <strong>" +
this.months + "</strong> <small>months</small><strong> " + this.days +
"</strong> <small>days</small> <strong>" + this.hours + "</strong> <small>hours</small> <strong>" +
this.minutes + "</strong> <small>minutes</small> <strong>" + this.seconds +
"</strong> <small>seconds</small>.";
var self=this;
setTimeout(function(){self.update(id);}, 1000);
}
</script>
</head>
<body >
<div>
<div id="counter" >Contents of this DIV will be replaced by the timer</div>
<script type="text/javascript">new CountUp('April 04, 2010 13:11:20','counter');</script>
</div>
<br>
<div>
<div id="counter" >Contents of this DIV will be replaced by the timer</div>
<script type="text/javascript">new CountUp('April 04, 2012 13:11:20','counter');</script>
</div>
</body>
</html>
And how to change to like->
<div id="counter" countup='April 04, 2012 13:11:20'><div>
as Compass already commented you are using the same id for both div elements for the counters.
Depending on your browser getElementById gives you just something with this id. In your case it seems to always be the first, so the second never gets used.

Categories

Resources