Search code examples
javascripttimebackgroundscale

Change background based on time and scale to browser window


So I'm looking to change the background of my webpage based on time. That is, one image for day and one image for night. There is a really good post I found on this site that works perfectly but I need it to do one more thing, scale the image with the browser window and not scroll with the page. The code I found for changing the background is

</body>
<script type="text/javascript">
    var currentTime = new Date().getHours();
    if(5 < currentTime && currentTime < 18){
        if (document.body) {
            document.body.background = 'images/bg-day.png';
        }
    } else {
        if (document.body) {
            document.body.background = 'images/bg-night.png';
        }
}
</script>
</html>

but I would like the images to scale with the browser window and stay fixed when scrolling so just my content scrolls. like this http://css-tricks.com/examples/FullPageBackgroundImage/css-2.php

At the moment I've got the full page background working fine but I would like it to change at night.

If someone could figure this out I would be forever in your debt.

Thanks


Solution

  • In your example page, you'll see that they put the background image in a div named bg and not document.body.background as in your time script. They then then set that div's css in the style tag at the top of the source. (Right-click and "View Source".)

    So if you want to mimic your example, create a div in your body like so:

    <body>
        <div id="bg">
            <img id="my-bg-image" src="images/bg-day.png" alt="">
        </div>
    </body>
    

    Then make sure that div has the scaling CSS that you want. A good place to start is, again, the example page:

        #bg {
            position:fixed; 
            top:-50%; 
            left:-50%; 
            width:200%; 
            height:200%;
        }
        #bg img {
            position:absolute; 
            top:0; 
            left:0; 
            right:0; 
            bottom:0; 
            margin:auto; 
            min-width:50%;
            min-height:50%;
        }
    

    And then, using a little jQuery magic (simply to make it easier), modify your time if statement to something like this:

    if(5 < currentTime && currentTime < 18){
        $('#my-bg-image').attr('src', 'images/bg-day.png');
    } else {
        $('#my-bg-image').attr('src', 'images/bg-night.png');
    }
    

    Don't forget to include jQuery if you decide to use it.