1

I have a web page where I would like the background image to be changed depending on user's daylight and darkness time. Is this possible? If so, can you give an example such JavaScript code? If not, how would the JS code look like if the day and night time depended on a location (city)? Thanks for any suggestions. P.S. I'm not including my code as the web page background has a simple HTML code for image background.

Dunno
  • 23
  • 4
  • Please read https://stackoverflow.com/help/how-to-ask on what kind of questions to be asked on SO. Note that Stackoverflow is not a coding service, so it's unlikely that somebody will just provide a working code for you without showing any effort. – Capricorn Jul 25 '18 at 12:49

3 Answers3

2

A more accurate alternative than relying on timezone could be to use the browser geolocation API locate the user and use a service to get the sunrise and sunset for that location

Either via a API service like https://sunrise-sunset.org/api or via your own server-side implementation using php's sunset() and sunrise() functions for example.

Capricorn
  • 2,061
  • 5
  • 24
  • 31
2

var now = new Date();
if (now.getHours() > 6 && now.getHours() < 20) {
  document.body.className += " day";
} else {
  document.body.className += " night";
}
.day {
  background-image: url("https://images.pexels.com/photos/125457/pexels-photo-125457.jpeg?cs=srgb&dl=blue-sky-bright-clouds-125457.jpg&fm=jpg");
  background-size: 100%;
}
.night {
  background-image: url("https://media.treehugger.com/assets/images/2016/06/milkyway.jpg.860x0_q70_crop-scale.jpg");
  background-size: 100%;
}

This gets the time using Javascript's Date object. There are 2 css classes, day and night which set the background image to either a day image or a night image. The javascript checks if it's between 7 AM and 7 PM. If it is, it adds the day class to the body and if it isn't it adds the night class. If you actually want to include real sunset and sunrise instead of hardcoded times then you might have to use some API.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

I think the easiest way to do it would be to get the users' time zone Getting the client's timezone in JavaScript and then choose a time at which it would switch. Say, 8:30 pm.