Search code examples
javascriptcssrandombackgroundcenter

how to center a random background in a javascript


I've looked on stackoverflow for a background js. After trying some I found what I thought was exactly what I need:

<script type="text/javascript">
ChangeIt();
</script>


<script type="text/javascript">
var totalCount = 8;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'http://adventureofucm.com/OtherSites/image_background/'+num+'.jpg';
document.body.style.repeat = "contain";// Background repeat
}
</script>

However, the backgrounds don't center, you just see 'em on the top left corner. So I googled on the net but... well idk anything about js, just a little few things. I'm helping a friend with his website and we're stuck on this. I'm just hoping someone with more knowledge than us can help by giving a look.

EDIT : Here's what i mean by "center" : https://i.sstatic.net/NQhMV.png


Solution

  • Here's a fiddle that uses css instead of js for this, also I've added a background-size on body so the entire image is visible on all screen sizes, this is optional however - http://jsfiddle.net/dk329q1L/

    Here's the css -

    body {
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover; /* Entire background image always stays in view */
    }