Using the time as css background color - javascript

Just for fun, I wanted to make my website have a dynamic background color that's an rgb value based on the current time. I did some googling and came up with the following, but it's not working.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Site</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link type="text/javascript" src="date.js">
<style>
p{
font-size: 150%;
}
</style>
</head>
<body>
</body>
</html>
date.js
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime(field) {
var now = new Date();
now = (now.getHours() * 10) + ', ' + (now.getMinutes() * 4) + ', ' + (now.getSeconds() * 4);
$(field).val(now);
}
document.getElementsByName("html").style.backgroundColor = "rgb(" + now + ")";
Can anyone help me with what I'm doing wrong, or an alternate/better way to do this?
I apologize if I did something stupid, I'm quite a javascript noob
Thanks in advance

Here. All jQuery. Code modified to work.
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime(field) {
var now = new Date();
now = (now.getHours() * 10) + ', ' + (now.getMinutes() * 4) + ', ' + (now.getSeconds() * 4);
$(field).val(now);
$('html,body').css({'background-color':'rgb('+now+')'});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Site</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link type="text/javascript" src="date.js">
<style>
p{
font-size: 150%;
}
</style>
</head>
<body>
<div id="idTimeField">20:10:34</div>
</body>
</html>

How about something like this:
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime() {
var now = new Date();
var R = (now.getHours() * 10) ;
var G = (now.getMinutes() * 4) ;
var B = (now.getSeconds() * 4);
document.body.style.backgroundColor = 'rgb(' + [R,G,B].join(',') + ')';
}

Your last line is out of function. And document.getElementByName doesn't work for html tag you should use document.getElementByTagName.
Overal use this instead
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime(field) {
var now = new Date();
now = (now.getHours() * 10) + ', ' + (now.getMinutes() * 4) + ', ' + (now.getSeconds() * 4);
$(field).val(now);
$('body').css('background-color', "rgb(" + now + ")");
}

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.

Tizen web app works on simulator, but doesn't work on gear 3

I'm trying to develop an app that reads data from the acceleration sensor, and save it on a text file. Using web app development, I've managed to make the app work on the emulator, but when I tried it on Samsung Gear 3 frontier, it didn't work. Can some figure out what I did wrong?
Below are the html and the java script code.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,user-scalable=no">
<title>Basic</title>
<link rel="stylesheet" href="lib/tau/wearable/theme/default/tau.min.css">
<link rel="stylesheet" media="all and (-tizen-geometric-shape: circle)" href="lib/tau/wearable/theme/default/tau.circle.min.css">
<!-- load theme file for your application -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="ui-page ui-page-active" id="main">
<header>
<h2 class="ui-title">TAU Basic</h2>
</header>
<div class="ui-content ui-content-padding">
<p id="readings"> Basic </p>
</div>
</div>
<script src="lib/tau/wearable/js/tau.min.js"></script>
<script src="js/app.js"></script>
<script src="js/lowBatteryCheck.js"></script>
<script src="js/circle-helper.js"></script>
</body>
</html>
Java script code:
function init() {
console.log("app started");
document.getElementById("readings").innerHTML="Starting";
accelerationSensor=tizen.sensorservice.getDefaultSensor("ACCELERATION");
if (accelerationSensor){
console.log("Sensor captured");
}
/* Update the clock hands every second */
accelerationSensor.start(onsuccessCB);
setInterval(function() {
updateTime();
}, 1000);
}
window.onload = init();
function onGetSuccessCB(sensorData)
{
var datetime = tizen.time.getCurrentDateTime();
var Date = ("0" + datetime.getHours()).slice(-2) + ":" +
("0" + datetime.getMinutes()).slice(-2) + ":" +
("0" + datetime.getSeconds()).slice(-2);
console.log(Date);
console.log("######## Get acceleration sensor data ########");
console.log("x: " + sensorData.x);
console.log("y: " + sensorData.y);
console.log("z: " + sensorData.z);
x = sensorData.x;
y = sensorData.y;
z = sensorData.z;
tizen.filesystem.resolve("documents", function(dir)
{
var newFile = dir.resolve("newFilePath.txt");;
newFile.openStream(
"a",
function(fs) {
fs.write(Date+"\t x:"+x+"\t y:"+y+"\t z:"+z+"\n");
fs.close();
}, function(e) {
console.log("Error " + e.message);
}, "UTF-8");
},function(){
document.getElementById("readings").innerHTML="Error";
});
document.getElementById("readings").innerHTML="Reading";
}
function onerrorCB(error)
{
console.log("error occurred: " + error.message);
}
function onsuccessCB()
{
console.log("acceleration sensor start");
var datetime = tizen.time.getCurrentDateTime();
var hour = datetime.getHours(),
var minute = datetime.getMinutes(),
var second = datetime.getSeconds();
tizen.filesystem.resolve("documents", function(dir)
{
newFile = dir.createFile("newFilePath.txt");
newFile.openStream(
"w",
function(fs) {
fs.write(hour+":"+minute+":"+second+"\tstart of recording \n");
fs.close();
}, function(e) {
console.log("Error " + e.message);
}, "UTF-8");
},function(){
document.getElementById("readings").innerHTML="Error";
});
}
function updateTime() {
accelerationSensor.getAccelerationSensorData(onGetSuccessCB, onerrorCB);
}
(function () {
window.addEventListener("tizenhwkey", function (ev) {
var activePopup = null,
page = null,
pageid = "";
if (ev.keyName === "back") {
activePopup = document.querySelector(".ui-popup-active");
page = document.getElementsByClassName("ui-page-active")[0];
pageid = page ? page.id : "";
if (pageid === "main" && !activePopup) {
try {
tizen.application.getCurrentApplication().exit();
} catch (ignore) {
}
} else {
window.history.back();
}
}
});
}());
Thanks in advance.
I've managed to find the solution, and I post it for helping others who would face the same issue.
It turns out that there is no acceleration sensor in S3, and everything works fine when I change the sensor from Acceleration to linear_acceleration. The codes for both html and javascript are as follow:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,user-scalable=no">
<title>Basic</title>
<link rel="stylesheet" href="lib/tau/wearable/theme/default/tau.min.css">
<link rel="stylesheet" media="all and (-tizen-geometric-shape: circle)" href="lib/tau/wearable/theme/default/tau.circle.min.css">
<!-- load theme file for your application -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="ui-page ui-page-active" id="main">
<header>
<h2 class="ui-title">TAU Basic</h2>
</header>
<div class="ui-content ui-content-padding">
<p id="readings"> Basic </p>
</div>
</div>
<script src="lib/tau/wearable/js/tau.min.js"></script>
<script src="js/app.js"></script>
<script src="js/lowBatteryCheck.js"></script>
<script src="js/circle-helper.js"></script>
</body>
</html>
The javascript:
var accelerationSensor;
function onsuccessCB() {
console.log("acceleration sensor start");
var datetime = tizen.time.getCurrentDateTime();
var hour = datetime.getHours();
var minute = datetime.getMinutes();
var second = datetime.getSeconds();
tizen.filesystem.resolve("documents", function(dir) {
var newFile = dir.createFile("newFilePath.txt");
newFile.openStream(
"w",
function(fs) {
fs.write(hour + ":" + minute + ":" + second + "\tstart of recording \n");
fs.close();
document.getElementById("readings").innerHTML = "Reading";
},
function(e) {
document.getElementById("readings").innerHTML = "File Error";
}, "UTF-8");
});
}
function init() {
console.log("app started");
document.getElementById("readings").innerHTML = "Starting";
accelerationSensor = tizen.sensorservice.getDefaultSensor("LINEAR_ACCELERATION");
document.getElementById("readings").innerHTML = "Starting1";
if (accelerationSensor) {
console.log("Sensor captured");
document.getElementById("readings").innerHTML = "Acceleration";
} else {
document.getElementById("readings").innerHTML = "Error";
}
/* Update the clock hands every second */
accelerationSensor.start(onsuccessCB);
document.getElementById("readings").innerHTML = "onsuccessCB done";
console.log("onsuccessCB done");
setInterval(function() {
updateTime();
}, 1000);
}
window.onload = init();
function onGetSuccessCB(sensorData) {
var datetime = tizen.time.getCurrentDateTime();
var Date = ("0" + datetime.getHours()).slice(-2) + ":" +
("0" + datetime.getMinutes()).slice(-2) + ":" +
("0" + datetime.getSeconds()).slice(-2);
console.log(Date);
console.log("######## Get acceleration sensor data ########");
console.log("x: " + sensorData.x);
console.log("y: " + sensorData.y);
console.log("z: " + sensorData.z);
var x = sensorData.x;
var y = sensorData.y;
var z = sensorData.z;
tizen.filesystem.resolve("documents", function(dir) {
var newFile = dir.resolve("newFilePath.txt");
newFile.openStream(
"a",
function(fs) {
fs.write(Date + "\t x:" + x + "\t y:" + y + "\t z:" + z + "\n");
fs.close();
},
function(e) {
console.log("Error " + e.message);
}, "UTF-8");
}, function() {
document.getElementById("readings").innerHTML = "Error";
});
document.getElementById("readings").innerHTML = "Reading";
}
function onerrorCB(error) {
console.log("error occurred: " + error.message);
}
function updateTime() {
accelerationSensor.getLinearAccelerationSensorData(onGetSuccessCB);
}
(function() {
window.addEventListener("tizenhwkey", function(ev) {
var activePopup = null,
page = null,
pageid = "";
if (ev.keyName === "back") {
activePopup = document.querySelector(".ui-popup-active");
page = document.getElementsByClassName("ui-page-active")[0];
pageid = page ? page.id : "";
if (pageid === "main" && !activePopup) {
try {
tizen.application.getCurrentApplication().exit();
} catch (ignore) {}
} else {
window.history.back();
}
}
});
}());
The above code will get linear_acceleration sensor readings, and save them to a text file in "Documents" folder.
You need filesystem.read and filesystem.write privileges to have access to "Document" folder.

How do I add zeros before hours/minute/seconds when they are < 10 in Javascript?

I encountered a problem while trying to create a real-time-clock: I'm trying to show a zero before the number that represents minutes/hours/seconds when they are < 10, but the function doesn't work. May someone explain where I'm wrong and why please? Is it the poisition of the if statement or what? What does i represents?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
var currentDate = new Date();
var time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
function zeros(i) {
if (i < 10) {
return "0" + i;
} else {
return i;
}
}
startClock();
zeros();
</script>
</body>
</html>
Your zeros function takes a number and add a zero in front if the number is < 10.
You need to call your zeros function when you set the time to convert hours, minutes, and seconds to zero-added form.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
var currentDate = new Date();
var time = zeros(currentDate.getHours()) + ":" + zeros(currentDate.getMinutes()) + ":" + zeros(currentDate.getSeconds());
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
function zeros(i) {
if (i < 10) {
return "0" + i;
} else {
return i;
}
}
startClock();
zeros(); // this doesn't do anything????
</script>
</body>
</html>

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.

Why does getting a LocalStorage item yield “undefined”?

We are using PhoneGap to develop a pedometer app using the iPhone accelerometer.
Below is a copy of the code we are currently running:
<!DOCTYPE html>
<html>
<head>
<title>Accelerometer</title>
<script type="text/javascript" charset="utf-8" src="js/cordova-1.7.0rc1.js"></script>
<script type="text/javascript" charset="utf-8">
// The watch id references the current `watchAcceleration`
var watchID = null;
var stepCount = 0;
window.localStorage.setItem('exp');
var expGain = 0;
var totalExp = window.localStorage.getItem('exp');
var userAge = window.localStorage.getItem('age');
var handicap = 0;
if (userAge <= 10) {
handicap = 10;
} else if (userAge > 10) {
handicap = 5;
}
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//e7
function onDeviceReady() {
startWatch();
}
// Start watching the acceleration
//
function startWatch() {
// Update acceleration every 5 seconds
var options = {
frequency: 1000
};
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
// Stop watching the acceleration
//
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
//count steps and calculate experience gained
function countSteps(accelx, timestamp, expGain, totalExp) {
var element = document.getElementById('accelerometer');
//var accCount = Math.round(acceleration.x);
//stepCount = stepCount + Math.abs(accCount);
stepCount = stepCount + 1;
expGain = stepCount * handicap;
totalExp = totalExp + expGain;
//window.localStorage.setItem('exp', totalExp);
element.innerHTML = '<br>Step Count: ' + stepCount + '<br/>' +
'Acceleration X: ' + Math.abs(accelx) + '<br />' +
'Timestamp: ' + timestamp + '<br />' +
'Experience: ' + totalExp + '<br />';
}
// onSuccess: Get a snapshot of the current acceleration
//
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');
var accelx = Math.round(acceleration.x)
var timestamp = acceleration.timestamp
//element.innerHTML = 'Acceleration X: ' + Math.abs(accelx) + '<br />' +
//'Acceleration Y: ' + acceleration.y + '<br />' +
//'Acceleration Z: ' + acceleration.z + '<br />' +
//'Timestamp: ' + acceleration.timestamp + '<br />';
if (Math.abs(accelx) > 1) {
countSteps(accelx, timestamp, expGain, totalExp);
}
}
// onError: Failed to get the acceleration
//
function onError() {
alert('onError!');
}
</script>
<link media="only screen and (max-device-width: 480px)" href="css/iPhone.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="accelerometer">Waiting for accelerometer...</div>
<button onclick="startWatch();">Start Watching</button>
<button onclick="stopWatch();">Stop Watching</button>
<br />
<p>back
</p>
</body>
</html>
The issue is: we keep getting an "undefined" next to our result for window.localStorage.setItem('exp');. We have been working all day to try and work this one out.
setItem takes two arguments (a key and a value). If you don't specify an argument, then undefined is the default value.
window.localStorage.setItem('exp'); means window.localStorage.setItem('exp', undefined);
If you want it to have some other value, then you need to specify it.
Doesn't localStorage.setItem require a second parameter? Have you tried:
window.localStorage.setItem("exp","");

Categories

Resources