Search code examples
jqueryrandombackground-image

Random background image AND corresponding style


I am implementing this Simple Image Randomizer to load random images from a list for my body.

var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];
$('body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() *      images.length)] + ')'});

Problem is, each of the images is prepared to sit in one specific corner of the screen. How would I add a corresponding list, which stores the background styles for each image, and how would I reach this over to the script? I also tried to enhance the script manually to sth like

  $('body').css({'background': 'url(images/' + images[Math.floor(Math.random() *      images.length)] + ')' + "no-repeat fixed top left});

..but that also seems not to work. And it would only be half the battle.


Solution

  •     $(function(){
            var positions = ['top-left-', 'top-right-', 'bottom-left-', 'bottom-right-'];
    
            var images = {
                'top-left-' : [1,2,3],
                'top-right-' : [4,5,6],
                'bottom-left-' : [7,8,9],
                'bottom-right-' : [10,11,12]
            };
    
            function randomize(){
                for(var i = 0; i < positions.length; i++ ){
                    var pos = positions[i];
                    var random_image = images[pos][Math.floor(Math.random() * images[pos].length)];
                    $('<div style="position:absolute;width:400px;height:200px;z-index:1;background:url(images/' + random_image + '.jpg) no-repeat top left;'+ pos.replace(/-/ig, ':0px;')+'"></div>').appendTo('body');
            }
        }
        randomize();
    });