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";
}
}
Related
I have been trying to get my page to refresh at midnight, but the code I wrote is not working.
This is the code that I have written:
function reloadClock() {
var reloadTime = new Date();
var hrs = reloadTime.getHours();
var min = reloadTime.getMinutes();
var sec = reloadTime.getSeconds();
// I tried this code, it will not work.
if (hrs == 0 && min == 0 && sec == 0) {
alert('this page will now reload');
location.reload();
}
// I also tried this code, still can't get it to work.
if (hrs == 14) { // Works as intended.
alert(hrs);
if (min == 31) { // Works as intended.
alert(min);
if (sec == 0) { // Does not work as intended.
alert(sec);
location.reload();
}
}
}
setTimeout(reloadClock(), 1000);
}
Does anyone know a solution for this?
check this
const timerefresh = setInterval(function(){
const time_ = new Date().toLocaleString('en-GB'); // return 24 hour time format in string, explaination about en-GB you can search on wikipedia, thats bored (:
let date = time_.split(', ')[0].split('/'); // split the time strings to get date in array [day, month, year]
let clock = time_.split(', ')[1].split(':'); // split the time strings to get clock in array [hour, min, sec]
countDownTime(Number(clock[0]),Number(clock[1]),Number(clock[2]));
document.getElementById('time1').innerHTML = 'date:'+date+', clock:'+clock;
},1000);
function countDownTime(h,m,s){
// some match to reverse the clock
document.getElementById('time2').innerHTML = 'countdown to midnight : '+ (23-h)+':'+(59-m)+':'+(60-s);
if(h === 23 && m === 59 && s === 59){ itsMidnight(); } // call its midnight 1 sec before clock 00:00:00
}
function itsMidnight(){
// its midnight, your function here
console.log('midnight! reload.')
window.location.reload();
}
// code below just for testing, you can delete it
let sectomidnight = 50;
function gotoMidnight(){
clearInterval(timerefresh);
setInterval(function(){
sectomidnight += 1;
countDownTime(23,59,sectomidnight);
},1000);
}
<div id="time1"></div>
<div id="time2"></div>
<button onclick="gotoMidnight();">goto 10 sec before midnight</button>
I am attempting to code a webpage whose background changes based on time of day, using javascript. I am aware there are other questions based around this concept, but my code, based on those questions' answers, does not produce results.
var background = ","
var time = new Date();
var greeting = '';
var hour = time.getHours();
if (hour < 6 || hour === 12) {
greeting = "Goodnight!";
background = 'assignment02_images/backgrounds/night.png';
}
else if (hour >= 6 && hour <12) {
greeting = "Good Morning!";
background = 'assignment02_images/backgrounds/morning.png';
}
else if (hour >=12 && hour < 18 ) {
greeting = "Good Afternoon!";
background = 'assignment02_images/backgrounds/afternoon.png';
}
else {
greeting = "Good Evening!";
background = 'assignment02_images/backgrounds/evening.png';
}
The greeting variable works, which is why I thought the background image should too. However, I don't know what I need to put in document.write() in order to get the background to show up. Currently this just displays a white background.
<div class="bg" id="bgImg"></div>
In your scriipt file
var dt = new Date()
setTimeout(function() {
console.log(dt.getHours())
if (dt.getHours() >= 1 && dt.getHours() <= 6) {
document.getElementById("bgImg").style.backgroundImage = "url('https://dummyimage.com/300x200/345fa1/fff')"
} else if (dt.getHours() >= 6 && dt.getHours() <= 12){
document.getElementById("bgImg").style.backgroundImage = "url('https://dummyimage.com/300x200/a13557/fff')"
}
}, 30)
Just check time between hours and add it into timeout
Fiddle Example
How can I dynamically change the gradient in the body with js based on time of day?
Thanks
—
Img
http://a1.dspncdn.com/media/692x/da/dc/4e/dadc4ed5117d4a8cc582199bb3ac9c68.jpg
use the following code
HTML
<div id='time'>
</div>
JavaScript
var d = new Date();
var time = d.getHours();
var div=document.getElementById('time');
if (time < 12)
{
div.style.backgroundImage ="url('morning image')";
}
if (time >= 12 && time < 3)
{
div.style.backgroundImage ="url('afternoon image')";
}
if (time > 3)
{
div.style.backgroundImage ="url('http://a1.dspncdn.com/media/692x/da/dc/4e/dadc4ed5117d4a8cc582199bb3ac9c68.jpg')";
}
CSS
#time{
height:400px;
width:400px;
}
refer this fiddle
It might help to have a look at https://stackoverflow.com/a/4358182/2588199 and then either set a different background or a css gradient string.
Something like:
var currentTime = new Date().getHours();
//Change here to set the hours to wish to change between
if (7 <= currentTime && currentTime < 20) {
//place image or strng here
}else {
//Place image or string here
}
Ok, I have a website for a restaurant. Right now I have a simple if statement in javascript that changes a piece of text from Were open to Were Closed depending on the time of day. But If on a mobile phone when you close your browser it still technically is open in the background. So if you reopen the browser it will say were open after the time it should say were closed until you refresh the page. I would like to find a way to get it to update in real time. I have tried using setInterval and setTimeout to accomplish this as well as a while loop but so far, nothing. I mean when I use setInterval i can print the time and it will increment in real time. So why cant it run my if statement each second and print the desired piece of text.
Here is my code that just displays it as of now.
var date = new Date().getHours();
if ((date > 9) && (date < 20) && (day != 0)) {
y="<span style=\"color:#07ed11\">We're Open!</span>";
}
else {
y="<span style=\"color:#fc4b1c\">Sorry we're Closed.</span>";
}
document.getElementById("open-close").innerHTML=y;
I just want it to print our in real time so that I can watch it change from open to close once the time hits it right
jsFiddle example
New version
I took the liberty of going back and revising this. I think this version will work better
var checkOpenStatus = function () {
var d = new Date();
var date = d.getHours();
var day = d.getDay();
if ((date > 9) && (date < 20) && (day != 0)) {
y = "<span style=\"color:#07ed11\">We're Open!</span>";
} else {
y = "<span style=\"color:#fc4b1c\">Sorry we're Closed.</span>";
}
document.getElementById("open-close").innerHTML = y;
setTimeout(checkOpenStatus,15000);
};
checkOpenStatus();
It runs every 15 seconds rather than every 100 milliseconds.
Old Version
Try this
var checkOpenStatus = function () {
var d = new Date();
var date = d.getHours();
var day = d.getDay();
if ((date > 9) && (date < 20) && (day != 0)) {
y = "<span style=\"color:#07ed11\">We're Open!</span>";
} else {
y = "<span style=\"color:#fc4b1c\">Sorry we're Closed.</span>";
}
document.getElementById("open-close").innerHTML = y;
}
setInterval(checkOpenStatus,100); //removed anon function
It updates every 100 milliseconds on the setInterval. You can change it to be faster or slower according to your preference.
var checkOpenStatus =function () {
var d = new Date();
var date = d.getHours();
var min = d.getMinutes();
if ((date>7 || (date == 7 && min >= 30)) && (date < 22) && (day != 0)) {
y = "<span style=\"color:#07ed11\">We're Open!</span>";
} else {
y = "<span style=\"color:#fc4b1c\">Sorry we're Closed.</span>";
}
document.getElementById("open-close").innerHTML = y;
};
checkOpenStatus();
Less intrusive closure style:
var updateElement = function($el) {
return function updater() {
$el.text(new Date()); // dummy, your logic goes here...
setTimeout(updater, 100);
}
}
var fooUpdater = updateElement($("#foo"));
setTimeout(fooUpdater,1000)
I'm displaying a message between Saturday at 6pm and Sunday 4am. The last time I had to do this it didn't work because I didn't take into account UTC time going negative when changing it to NYC time.
I am doing the math right (displaying at the appropriate times)?Should I put the UTC conversion code into its own function? Is this the worst js you've ever seen?
-- jquery is called --
$(document).ready(function() {
var dayTime = new Date();
var day = dayTime.getUTCDay();
var hour = dayTime.getUTCHours();
//alert(day.toString()+" "+hour.toString());
if (hour >= 5){
hour = hour-5;
}
else{
hour = hour+19;
if(day > 0){
day--;
}
else{
day = 6;
}
}
//alert(day.toString()+" "+hour.toString());
if ((day == 6 && hour >= 18) || (day == 0 && hour < 4)){
}
else{
$('#warning').hide(); //Want this message to show if js is disabled as well
}
});
Why do you even need that UTC stuff? Just work with local time:
var day = dayTime.getDay();
var hour = dayTime.getHours();
And you can clean up that conditional a bit too:
if (!(day == 6 && hour >= 18) && !(day == 0 && hour < 4)) {
$('#warning').hide();
}
This should get you your server's time:
var dayTime = new Date();
localOffset = dayTime.getTimezoneOffset() * 60000;
serverOffset = 5 * 60 * 60000;
dayTime = new Date(dayTime.getTime() + (localOffset - serverOffset));
Play around with that "5" in the server offset; it's the hours. It may need to be a -5; I'm not really sure.
Also, that's going to break every daylight savings. You'll have to detect that somehow and modify serverOffset.