Changing background Javascript project - javascript

I'm trying to make a background that changes the color on the time of day. However I can't seem to fix my parameters. Put them in variables. Input from HTML to JavaScript is fixed.
Feels like I'm missing something very obvious. (new to JavaScript and coding in general).
jQuery(document).ready(function($) {
function alerts(alert1, alert2, alert3, alert4, alert5, alert6) {
var hours = new Data().getHours();
if (alert1.empty() || alert2.empty() || alert3.empty() || alert4.empty() || alert5.empty() || alert6.empty()) {
alert1 = 0;
alert2 = 12;
alert3 = 12;
alert4 = 17;
alert5 = 17;
alert6 = 24;
if (hours >= alert1 && hours < alert2) {
document.body.style.backgroundColor = "#fceea1";
} else if (hours >= alert3 && hours < alert4) {
document.body.style.backgroundColor = "#dbbc0a";
} else if (hours >= alert5 && hours < alert6) {
document.body.style.backgroundColor = "#706527";
} else {
}
}
};
body {
font-family: sans-serif;
background: white;
font-size: 150px;
color: #333;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welkom</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js">
alerts(0, 12, 12, 17, 17, 20);
</script>
</body>
</html>

The working code, explanations are after the code:
index.html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Welkom</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <!-- Includes Jquery -->
<script src="js/index.js"></script> <!-- Includes the script for background change -->
</body>
</html>
js/index.js
jQuery(document).ready(function( $ ){
function alerts (alert1, alert2, alert3, alert4) {
var hours = new Date().getHours(); //The proper inclusion of date
if (alert1 == undefined) { //Undefined is JS keyword which set
alert1=0; //when variable was declared, but undefined, no defenition
}
if (alert2 == undefined) {
alert2=12;
}
if (alert3 == undefined) {
alert3=17;
}
if (alert4 == undefined) {
alert4=24;
}
//The redundant variables were removed and you can reuse variable
// for multiple if statements
if (hours >= alert1 && hours < alert2) {
document.body.style.backgroundColor = "#fceea1";
} else if (hours >= alert2 && hours < alert3) {
document.body.style.backgroundColor = "#dbbc0a";
} else if (hours >= alert3 && hours < alert4) {
document.body.style.backgroundColor = "#706527";
} else { //Just a quick comment, you are able not to even print
// else statement, you can just leave it out
}
}
alerts(); // Calls the function
}); // the ) bracket closes Jquery
css/style.css
body {
font-family: sans-serif;
background: white;
font-size: 150px;
color: #333;
} /*Unchanged*/
Explanations
There was 5 main problems with your code.
First:
The 'if' statement
Your 'if' statement for checking if the values were empty ALSO included the code for execution the function itself.
So if you called your code with variables set, the code won't execute.
Second:
The wrong import of jQuery
What you actually meant was var hours = new Date().getHours(); instead of var hours = new Data().getHours();.
Its very simple error, easy fix.
Third:
alert1.empty()
This is not correct approach. Much cleaner is to to check like alert1 == undefined.The undefined keyword is for variable which were declared, but they haven't been defined. Plus not all JavaScript interpreters (browsers) support .empty().
Fourth:
The or in the 'if' statement
The operator || is evil. In code example you provided if any of those variables missed it will override ALL variables to default values you specified. Because of that I have divided them in separate 'if' statements.
Fifth:
Redundant variables
The variables alert2 and alert3 are redundant, like variables alert4 and alert5. By redundant I mean they have the same value, while you can just use one variable, but in multiple 'if' statements. Remember: You can use the same variable in multiple 'if' statements. I removed two variables and modified version of the code execution is:
if (hours >= alert1 && hours < alert2) {
document.body.style.backgroundColor = "#fceea1";
} else if (hours >= alert2 && hours < alert3) {
document.body.style.backgroundColor = "#dbbc0a";
} else if (hours >= alert3 && hours < alert4) {
document.body.style.backgroundColor = "#706527";
} else {
}

I think experimenting with random little projects is a great way to learn, so I made a simple script that does what you described with comments so you can try to understand how everything works!
The color looks pretty odd and ugly, but that's just because of the values I gave it, so feel free to mess around with weights and different measurements of time!
function changeColor() {
var d = new Date(); // Creates a 'date' object
var ms = d.getMilliseconds(); // Gets the current millisecond
var minute = d.getMinutes(); // Gets the current minute
var second = d.getSeconds(); // Gets the current second
/*
Other methods of obtaining the time:
d.getFullYear() Get the year as a four digit number (yyyy)
d.getMonth() Get the month as a number (0-11)
d.getDate() Get the day as a number (1-31)
d.getHours() Get the hour (0-23)
d.getTime() Get the time (milliseconds since January 1, 1970)
d.getDay() Get the weekday as a number (0-6)
*/
document.body.style.backgroundColor = 'rgb(' + ms/4 + ',' + minute + ',' + second + ')';
// This sets the backgroundColor of the document to an RGB value where red is the milliseconds, green is the minute, and blue is the second
// Note: I divided the millisecond value by 4 because the highest possible value is 255 and the millisecond value can reach 999.
// It would still work without dividing it, but the color wouldn't change as much because it would interpret 255-999 as 255
}
var interval = setInterval(changeColor, 100) // Runs the changeColor() function every .1 seconds
// Note: This would still work if I didn't set it as a variable, but it's good practice to set intervals as variables so you can use clearInterval(variable)

Related

Class change based on local time : local sunrise/sunset calculation?

I'm new to JavaScript and put together this code to change the background on my page based on visitors local time.
I can't really test it yet, so first question would be, is this actually working? :D
And the main question: is there a way to set the sunrise and sunset times (set to 6 and 20 now) to follow the actual local times of the visitor?
Any help very much appreciated!!
<script type="text/javascript">
setInterval(change_background, 1000 * 60 * 60);
function change_background() {
var d = new Date();
var n = d.getHours();
console.log(n);
if (n == 6 || n == 20) {
document.getElementById("intro").className = "inter";
} else {
if (n == 23 || n < 7) {
document.getElementById("intro").className = "night";
} else {
document.getElementById("intro").className = "day";
}
console.log("test");
}
console.log("test");
}
change_background();
</script>
I suggest this shorter and reordered code – main difference is we set the class each time the function is called, your code would not have done anything after hour 7, execpt in exactly the hours 6, 20 and 23.
function change_background() {
var nowHour = new Date().getHours();
document.querySelector("#intro").className = ( nowHour >= 6 && nowHour <= 20 ) ? "inter" : ( (nowHour >= 23 || nowHour <= 5) ? "night" : "day" );
}
setInterval(change_background, 1000 * 60 * 60); change_background(); // trigger interval and first check
To use the local timezone you can use getTimezoneOffset – but things can become nightmarish with timezones, if you want to be as near to accurate as you can get. Just think about a science station in the polar regions, sunrise and sunset lose their meaning in such extreme scenarios. But with the offset you can use that to link it to a known good sunrise time .. but then you need to edit your file every day (or at least couple of days) to match the progression throughout the year.

JS Light bulb switch on/off on daytime

I am getting into javascript and recently bumped into if statements. My isssue is that lightbulb should be either switched on/off based on time of the day. So if the time is equal or greater than 10 and equal or lesser than 15.00, it going to be on, else its gonig to be off. For some odd reason it won't switch from the off one. Here is mycode:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" onload="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<script>
var image = document.getElementById('myImage');
var hour = now.getHours();
function changeImage() {
if (hour >= 10 && <= 15) {
image.src = "pic_bulbon.gif";
}
else {
image.src = "pic_bulboff.gif";
}
}
</script>
</body>
</html>
So you did a few things wrong:
If you want to use date, you first need to declare a var with the value of new Date. You can learn more about that here
your if statement had two faults
fault 1: (hour >= 10 && <= 15) after && you forgot to set the value 15 needs to be langer then. correct way would have been (hour >= 10 && hour <= 15)
fault 2: is that if you use && it means both conditions must be true. Which is not what you want. You want to use || which means or. Either hour >= 10 is true or hour >= 15
Also you need to execute your function or it won't work, and onload on an img as the way you are using it won't work. You can however run it by placing changeImage(); underneath your func.
var image = document.getElementById('myImage');
var date = new Date();
var hour = date.getHours();
function changeImage() {
if (hour >= 10 || hour <= 15) {
image.src = "pic_bulbon.gif";
}
else {
image.src = "pic_bulboff.gif";
}
}
changeImage();
fiddle
I tweaked the code a bit, now it works as intended. I had to use && because the condition is set to time between 8 and 14 (8,9,10,11,12,13,14) - on these hours bulb will be off, else it will be on.
var image = document.getElementById('myImage');
var hour = new Date();
hour = hour.getHours();
function changeImage() {
if (hour >=8 && hour <= 14 ) {
image.src = "http://blogdecorwatts.com/wp-content/uploads/2017/02/tipos-del%C3%A2mpadas-incandescentes.jpg";
} else {
image.src = "https://www.educolorir.com/imagem-lampada-ligada-dm26249.jpg";
}
}

Javascript not running Prestashop

Im trying to add a countdowns shipping time, using this code: http://jsfiddle.net/37ox54bk/7/
I use the HTML box module: https://mypresta.eu/modules/front-office-features/html-box.html
The code looks like this:
<div id="countdownTimer">0</div>
<script type="text/javascript">// <![CDATA[
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
var timerRunning = setInterval(
function countDown() {
var target = 15; // 15:00hrs is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
if(weekday == 0){//Sunday? Add 24hrs
target += 24;
}//keep this before the sunday, trust me :>
if(weekday == 6){//It's Saturday? Add 48hrs
target += 48;
}
//If between Monday and Friday,
//check if we're past the target hours,
//and if we are, abort.
if((weekday>=1) && (weekday<=5)){
if (now.getHours() > target) { //stop the clock
return 0;
}
}
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}, 1000
);
}// ]]></script>
But nothing is happening, it just shows 0 like the javascript is not running.
Anyone got any idea?
It looks like that module wraps everything inside <script> tags in
// <![CDATA[
//--><![CDATA[//><!-- //
[your code]
//--><!
// ]]>
It doesn't look like that's even the correct way to use CDATA but in any case i think all this achieves in your case is commenting the whole piece of code out.
Do you not have access to the files in your theme? You could for instance still add the <div id="countdownTimer">0</div> with the module and paste your code into the document.ready(); function of the globals.js
Try to make a js file and link it like this:
<script src="http://yoursite.com/folder/file.js"></script>
<div id="countdownTimer">0</div>
And if you need to add some css code you have to add it on your current css prestashop file (for example if you need to add it on your homepage so you've to work on golbal.css)
Hope it can help you

Change CSS of HTML on computer timing

I have three CSS with me in one HTML, morning.css, evening.css & night.css..
My requirement is that, once visitor visits the website, the css should change according to visitor PC timing...
Morning.css --> 6.00hrs - 15.00hrs
Evening.css --> 15.00hrs - 19.00 hrs
Night.css --> 19.00hrs - 6.00hrs
Can anyone help me with this..??? My requirement is on load not on button click
You can write a function which will set the class to body like the following:
function setTimingClass() {
var hour = new Date().getHours();
var cls;
if (hour >= 6 && hour <= 14) {
cls = 'morning';
} else if (hour >= 15 && hour <= 18) {
cls = 'evening';
} else {
cls = 'night';
}
document.body.className = document.body.className + ' ' + cls;
}
And call the function on body's onload. And then use this classes in your css file to style accordingly
You can use for example function like this:
function applyClass(){
var date = new Date();
var hour = date.getHours();
if(hour >= 6 && hour < 15) {
// apply 'morning' class to body
} else if(hour >= 15 && hour < 19) {
// apply 'evening' class to body
} else {
// apply 'night' class to body
}
}
How to append class to DOM element you can easily find on another thread of stackoverflow
With this function you can check time and class to the dom element
(function(){
var currentdate = new Date();
var datetime = currentdate.getHours();
if(datetime >=6 && datetime<15){
// moning class
}
else if(datetime >=15 && datetime<19){
// evening classes
}
else{
// night class
}
alert(datetime)
}());
jsfiddle
You need to use JS or any other programming language like php to achieve this.
For me easiest way will be loading all 3 scripts and adding class to body depands on hour.
<script>
window.onload = function(){
var d = new Date();
var h = d.getHours();
if(h >= 6 && <= 15) {
document.body.setAttribute('class','morning');
}
}
</script>

connect html with javascript Date object

i'm trying to build a page that takes the current hour and minute from the javascript date module and then makes the background color unique based off of that info.
what needs to change to get the html liked with the javascript? (new to this if you cant tell).
HTML
<html>
<head>
<meta charset="UTF-8">
<title>New color for each minute of day</title>
</head>
<body id="body">
<script src="script.js"></script>
</body>
</html>
JAVASCRIPT
var body = document.getElementById("body");
var a = 0;
var b = 0;
var c = 0;
function currentTime() {
var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();
minute = formatTime(minute);
text.innerHTML = hour + ":" + minute;
return minute
}
function changeColor() {
for (minute =< 59; a + 1);
for (hour =< 24; b + 10);
}
function setScene() {
timeValue = currentTime();
}
window.addEventListener("load", initialScene, false);
document.body.style.backgroundColor= 'rgb(' + a + ',' + b + ',' + c + ')';
Omit the CSS (style tag) in the first example and just use plain JS.
document.getElementsByTagName("body")[0].style.background="rgb("+a+", "+b+", "+c+");";
should do it
That's the main problem. Also, in your changeColor function, you are not using the for loop correctly, although you've got the right idea.
for (minute=0;minute<=59;minute+=1) {
a=minute;
}
for (hour=0;hour=<24;hour+=10) {
b=hour;
}
for loops can be a confusing subject for newcomers to JS, but there are some great tutorials online. Do a Google Search and really take the time to learn what a for loop does sometime, it's a good thing to know.
PS I don't see where c is defined.
I think you ask for a changing background for every minute of the day. You need to define a recurring function that reads the time and changes the color. You have that as setScene.
Now you can call it every 60 seconds automatically by pasting the following somewhere inside initialScene:
setInterval(setScene, 60000);

Categories