Random full-screen background image in browser update

Im using this script that I found online to have a random background image every time I refresh the browser.

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 great on screens larger than 1150 pixels, but least of all, images begin to accumulate one on top of the other. How can I make it stretch regardless of screen size. I don't care if the image is cropped on small screens while it fills the lot.

thanks

+4
source share
3 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); }); 
+5
source

I found this article CSS3 random background images and this solved the problem

 <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> 

Anyway, thanks :)

+2
source

Use Falu's answer, which is considered correct, but use the CSS methods used as solution # 1 in this post. Perfect Full Page Background Image

 .imageCycle1{ background:url(bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='bg.jpg', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='bg.jpg', sizingMethod='scale')";} 

It works great for every screen size.

0
source

Source: https://habr.com/ru/post/1497578/


All Articles