Reputation: 1
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>
Upvotes: 0
Views: 86
Reputation: 854
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.
Upvotes: 1