$(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();
});
Random background image AND corresponding style
-
21-06-2023 - |
Question
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
OTHER TIPS
A possibility:
$('body').css({'background-image':'url(' + images[Math.floor(Math.random() * images.length)] + ')','background-repeat': 'no-repeat','background-position': '200px 70px'});
thanks go to aSeptik and his efforts.
I found the following to be working like I need it, based on his code:
$(function(){
var positions = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
var images = {
'top-left' : [7],
'top-right' : [0,5],
'bottom-left' : [2,4,6],
'bottom-right' : [1,3,8]
};
function randomize(){
var pos = positions[Math.floor(Math.random() * positions.length)];
var random_image = images[pos][Math.floor(Math.random() * images[pos].length)];
$('body').css('background', 'url("images/' + random_image + '.jpg") no-repeat ' + pos.replace(/-/, ' '));
}
randomize();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow