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
Related
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";
}
}
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>
So I'm trying to get a custom greeting depending on the user's calendar and clock. It used to work great, but I just copy pasted from some old code for my new site and it has ended up not displaying at all. Here's what I've got:
<script type="text/javascript">
var d=new Date();
var time=d.getHours();
var elem=document.getElementById('sunMoon')
if (time>=6 && time<=12)
{
elem.textContent = "testing";
}
if (time > 13 && time < 17)
{
elem.textContent = "Good afternoon!";
}
if (time > 18 && time < 24)
{
elem.textContent = "Good evening!";
}
if (time > 0 && time < 5)
{
elem.textContent = "Have a nice night!"
}
</script>
Ok, so suggestions followed, but I only get the same result-nothing. The above code has been edited to reflect the new formatting.
You're getting an element with an ID of sunMoon, but never using it. Instead, your code uses document.write. If you meant to put the text in that element, you should replace
document.write("...")
with
elem.textContent = "..."
It seems to work on this jsFiddle.
I replaced document.write with alert, so maybe that's causing you problems? Try using alert to see some feedback or looking at your console for debugging messages.
It's possible you don't have the "sunMoon" id element anymore in your markup.
Try this and see that it works: http://jsfiddle.net/82BTA/7/
HTML
<p><span id="sunMoon"></span>, user2757975.</p>
JS
var d=new Date();
var time=d.getHours();
var elem=document.getElementById('sunMoon')
if (time > 5 && time <= 12)
{
elem.textContent = "Good Morning!";
}
if (time > 12 && time <= 18)
{
elem.textContent = "Good afternoon!";
}
if (time > 18 && time <= 24)
{
elem.textContent = "Good evening!";
}
if (time > 0 && time <= 5)
{
elem.textContent = "Have a nice night!"
}
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.