Cannot read property 'textContent' of null at renderTime - javascript

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.

Related

Creating a clock with Vue.js

Recently I found a script and I started to develop it. But I am stuck with a problem.
My plan was to make a clock with Vue.js. But in this script the time is showing in 24 hours format. I need to make it 12 hours format.
Beside that I want to add different time zone on it like "Asia/Dhaka", "Asia/India", etc.
Here is the JavaScript code:
var clock = new Vue({
el: '#clock',
data: {
time: '',
date: ''
}
});
var week = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
var timerID = setInterval(updateTime, 1000);updateTime();
function updateTime() {
var cd = new Date();
clock.time = zeroPadding(cd.getHours(), 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds(), 2);
clock.date = zeroPadding(cd.getFullYear(), 4) + '-' + zeroPadding(cd.getMonth()+1, 2) + '-' + zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()];
};
function zeroPadding(num, digit) {
var zero = '';
for(var i = 0; i < digit; i++) {
zero += '0';
}
return (zero + num).slice(-digit);
}
For help I am also giving the HTML file below:
HTML:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Xenon Clock</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Share+Tech+Mono'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="clock">
<p class="date">{{ date }}</p>
<p class="time">{{ time }}</p>
<p class="text">Xenon Production</p>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
With some modifications from here:
function updateTime() {
var cd = new Date();
var hours = cd.getHours();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // The hour '0' should be '12'
clock.time = zeroPadding(hours, 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds(), 2) + ' ' + ampm;
clock.date = zeroPadding(cd.getFullYear(), 4) + '-' + zeroPadding(cd.getMonth()+1, 2) + '-' + zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()];
}
The HTML part doesn't change.

dynamic url with iframe using javascript in WordPress

The script in the html below works as expected. It loads the latest version of a page by getting today's date info and modifying the iframe src.
But when I put just the script into a WordPress code module for a section of a page, it takes over the whole page. I suspect the problem is the use of document.body.innerHTML, but I don't know what the correct javascript code is.
<html>
<head>
<title>Title</title>
</head>
<body>
<script type="text/javascript">
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
var h = h > 12 ? h - 12 + 'PM' : h + 'AM';
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = mm + '%2f' + dd + '%2f' + yyyy;
document.body.innerHTML += ' <iframe src="https://www.colorado.gov/airquality/site.aspx?aqsid=080770020&seeddate= ' + today + '" width = "100%" height ="600"> </iframe> ';
</script>
</body>
</html>
document.getElementsByClassName('et_pb_code_inner')[1].innerHTML += ' <iframe src="https://www.colorado.gov/airquality/site.aspx?aqsid=080770020&seeddate= ' + today + '" width = "100%" height ="600"> </iframe> ';

Time Over, Time Elapsed and Time Countdown on javascript to load in body in php

Please Help!
I want to load Time Over, Time Elapsed dan Time Countdown on web page when student do the exam, I always failed to show it when the web page (exam page) load.
are my script right?
<?php $waktu=60;?>
<script type="text/javascript">
var TimeOver = true;
function getJam(Tanggal)
{
Jam = (Tanggal.getHours() < 10) ? "0" + Tanggal.getHours() + ":" : Tanggal.getHours() + ":";
Jam += (Tanggal.getMinutes() < 10) ? "0" + Tanggal.getMinutes() + ":" : Tanggal.getMinutes() + ":";
Jam += (Tanggal.getSeconds() < 10) ? "0" + Tanggal.getSeconds() : Tanggal.getSeconds();
return Jam;
}
function dispJam()
{
TglCur = new Date();
var a = document.getElementById("Watch");
a.value = getJam(TglCur);
var b = document.getElementById("TimeTaken");
b.value = getWaktu(TglCur,TglStart);
var c = document.getElementById("TimeLeft");
if ((Tgl.getTime() - TglCur.getTime()) <= 0)
{
if(TimeOver) TimeOverWarn();
c.value = "Habis";
}
else
{
c.value = getWaktu(Tgl,TglCur);
setTimeout("dispJam()",1000);
}
}
function getWaktu(Tgl,TglCur)
{
TmLf = Tgl.getTime() - TglCur.getTime();
TmLfHours = Math.floor(TmLf/3600000) ;
TmLfMinutes = Math.floor((TmLf%3600000)/60000);
TmLfSeconds = Math.round((TmLf%60000)/1000);
TmLfStr = (TmLfHours < 10) ? "0" + TmLfHours + ":" : TmLfHours + ":";
TmLfStr += (TmLfMinutes < 10) ? "0" + TmLfMinutes + ":" : TmLfMinutes + ":";
TmLfStr += (TmLfSeconds < 10) ? "0" + TmLfSeconds : TmLfSeconds;
return TmLfStr;
}
function TimeOverWarn()
{
alert("\n Maaf " + <?php echo $nama?> + " ....\n Waktu Anda Habis");
TimeOver = true;
return true;
}
Tanggal = new Date();
Tgl = new Date();
TglStart = new Date();
ArrayBulan = new Array("Januari","Pebruari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","Nopember","Desember");
Tahun = Tanggal.getYear();
TglStr = Tanggal.getDate() + " " + ArrayBulan[Tanggal.getMonth()] + " " + Tahun;
Tgl.setTime(Tgl.getTime() + 60 * 60 * 1000);
</script>
<script language="javascript">
function selesai() {
document.ljkform.submit.click();
clearTimeout(timeID);
}
function timer() {
timeID=setTimeout("selesai()",60000 * <?php echo $waktu;?>);
}
</script>
I use these script in body load.
Here is my script to load it.
<body onLoad="dispJam();timer();">
<table>
<FORM NAME="User">
<tr><td><center>Sisa Waktu<br><INPUT TYPE="text" NAME="TimeLeft" id="TimeLeft" SIZE="8"></td></tr>
<tr><td><center>Waktu<br><INPUT TYPE="text" NAME="TimeTaken" id="TimeTaken" SIZE="8"></td></tr>
<tr><td><center>Sekarang Jam<br><INPUT TYPE="text" NAME="Watch" id="Watch" SIZE="8"></td></tr>
</FORM>
</table>
<form name="ljkform" method="post" action="hasil_tes.php?idtest=<?php echo $idtest;?>&idanggota=<?php echo $idanggota;?>">
<!-- script to show the question form -->
</form>
</body>
Many thanks before...

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>

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

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).

Categories

Resources