Changing background based on time of day (using javascript)

陌路散爱 提交于 2019-11-27 02:06:45

You don't need to use a new stylesheet for each image. You can change only the background image from javascript:

<html>
<head>
    <title></title>
</head>
<body>

</body>
<script type="text/javascript">
var currentTime = new Date().getHours();
if (7 <= currentTime && currentTime < 20) {
    if (document.body) {
        document.body.background = "http://itsnotch.com/tumblr/images/daytime_bg.jpg";
    }
}
else {
    if (document.body) {
        document.body.background = "http://itsnotch.com/tumblr/images/nighttime_bg.jpg";
    }
}

</script>
</html>

EDIT: updated to show the recommended location of the script inside the page. This has been tested and works in Firefox and Internet Explorer.

I'd recommend something slightly different than neo - rather than setting the image only, have two CSS classes, one for day and one for night - both can be in the same stylesheet. You can set the body's class depending on the time of day. This will allow you to do more than just the background.

document.body.className = "day";
or
document.body.className = "night";

I have two different background .jpgs that I want to used as the backgroud depending on what time of day it is.

I've written a more complete solution to this that can not only swap out an image for a night or day version, but select from pools of many images corresponding to all times of day.

It uses php for the sun data at your given coordinates and pure css to do the animations (no javascript).

for a demo see here:
http://shawnfromportland.com/circadianCssWithPhp/

for the source check it out here:
https://github.com/shawnfromportland/circadianCssWithPhp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!