Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random fullscreen background image on browser refresh

Im using this script that I found online to have a random background image on whenever the browser is refreshed.

CSS

body{ 
background: no-repeat center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

JS

$(document).ready(function(){
var images=['images/001.jpg',
            'images/002.jpg',
            'images/003.jpg',
            'images/004.jpg',
            'images/005.jpg',];

var randomNumber = Math.floor(Math.random() * images.length);
var bgImg = 'url(' + images[randomNumber] + ')';

$('body').css({'background':bgImg, 'background-size':'cover', });

});

Works fine on screens larger than 1150px but anything less than that, the images starts piling up one on top of another. How can I get this to stretch out no matter what screen size. I dont care if the image gets cropped on small screens as long as it fills the lot.

Thank you

like image 489
no0ne Avatar asked Aug 17 '13 12:08

no0ne


People also ask

How do I set a random background image in CSS?

jpg', 'bg-05. jpg', 'bg-06. jpg', 'bg-07. jpg' ); // array of filenames $i = rand(0, count($bg)-1); // generate random number size of the array $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen ?>

How do I stop my background from flickering to change?

Try to preload the image resource to the device storage by including the image in DOM like in the following HTML-Code. Maybe the error comes up because the image resource need to be loaded which takes some time (flickering).

How do I make my background image only appear once?

You have to set the background-repeat property to no-repeat . This will ensure that the background-image is not repeated. The image will only be shown once. To fit the image into each cell you can use background-size: cover and background-position: center .


Video Answer


2 Answers

Like this

DEMO

JS

$(document).ready(function(){
    var classCycle=['imageCycle1','imageCycle2'];

    var randomNumber = Math.floor(Math.random() * classCycle.length);
    var classToAdd = classCycle[randomNumber];

    $('body').addClass(classToAdd);

});
like image 65
Falguni Panchal Avatar answered Oct 12 '22 08:10

Falguni Panchal


I found this article Random background images CSS3 and this solved the issue

<html>
<head>
<script type="text/javascript"> 
var totalCount = 5;
function ChangeIt() 
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'images/'+num+'.jpg';
document.body.style.backgroundSize = "cover";// Background repeat
}
</script>
</head>
<body> 

// Page Design 
</body> 
<script type="text/javascript"> 
ChangeIt();
</script> 
</html>

Thank you anyway :)

like image 40
no0ne Avatar answered Oct 12 '22 08:10

no0ne