Creating a clock with Vue.js - javascript

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.

Related

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?

function show() {
var now = new Date();
var year = now.getFullYear(),
month = now.getMonth() + 1,
date = now.getDate(),
day = now.getDay(),
hour = now.getHours(),
minute = now.getMinutes(),
second = now.getSeconds(),
hour = check(hour);
minute = check(minute);
second = check(second);
var week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday\n"];
day = week[day];
var t = "Today is:" + year + "year" + month + "month" + date + hour + ":" + minute + ":" + second;
return t;
}
function check(i) {
if (i < 0) {
i = "o" + i;
}
return i;
}
var h = document.getElementById("show");
h.innerHTML = show();
var h = document.getElementById("show");
setInterval(function() {
h.innerHTML = show();
}, 1000);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../js/date.js"></script>
</head>
<body>
<div id="show"></div>
</body>
</html>
I hope to display the current system time on the web page using an external link method, but I don't know why an error occurs,Is it because of code error code? i think i need help,Please help me debug the code
You get that because you try to access your HTML element before the page has loaded. You can add the defer keyword at your html file in the script tag and it should be ok
<script src="../js/date.js" defer></script>

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> ';

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.

Data query to timeline chart

I need a help.
I would like to see the last 24 hours in the timeline Chart. This is the formatted datetime DD/MM/YYYY HH:MM:SS.
This is the data source: https://docs.google.com/spreadsheets/d/1H602ZpDfwl044qjDyIDfscOWoaSqLzjsvb3TuZXEK6c/edit#gid=0
I'm getting en error: Uncaught SyntaxError: Unexpected token ILLEGAL
Does anyone have any idea to solve this?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization',
'version':'1','packages':['timeline']}]}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataTable = new google.visualization.DataTable();
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1H602ZpDfwl044qjDyIDfscOWoaSqLzjsvb3TuZXEK6c/edit#gid=0');
var nowone = getNowDate();
query.setQuery("select A,B,C where B >= datetime '"+nowone+"' ");
query.send(handleQueryResponse);
}
function getNowDate(){
var d=new Date();
d.setDate(d.getDate() - 1);
var year = d.getFullYear();
var month = d.getMonth() + 1;
var day = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
var microsecond = d.getDate();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
if (hour.toString().length == 1) {
hour = '0' + hour;
}
if (minute.toString().length == 1) {
minute = '0' + minute;
}
if (second.toString().length == 1) {
second = '0' + second;
}
//while(microsecond.toString().length < 3) {
// microsecond = '0' + microsecond;
//}
var dateString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second';
return dateString;
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {
timeline: { singleColor: '#8d8' },
};
var container = document.getElementById('example5.2');
var chart = new google.visualization.Timeline(container);
chart.draw(data, options);
setTimeout(drawChart, 5000);
}
</script>
</head>
<body>
<div id="example5.2" style="height: 500px;"></div>
</body>
</html>
This is purely a JS issue. You have an extra quote in JS that doesn't belong. When you set your time, it should be:
var dateString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
Instead of
var dateString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second';
If you remove the extraneous quote, your error will go away.

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