Reputation: 953
On my login page, I want to create a function so that with each load, a new background image appears.
Upvotes: 1
Views: 624
Reputation: 17570
You can do it with onload method to body and using random to take from any array which includes of images
function randombg(){
var random= Math.floor(Math.random() * 6) + 0;
var bigSize = ["url('http://placehold.it/300&text=banner1')",
"url('http://placehold.it/300&text=banner2')",
"url('http://placehold.it/300&text=banner3')",
"url('http://placehold.it/300&text=banner4')",
"url('http://placehold.it/300&text=banner5')",
"url('http://placehold.it/300&text=banner6')"];
document.querySelector("body").style.backgroundImage=bigSize[random];
}
body{
width:100;
height:100
}
<body onload="randombg()">
</body>
Upvotes: 2
Reputation: 820
You would need to do something like this:
const imageUrls = [
'url1',
'url2',
'url3'
];
const randomImageIndex = Math.floor(Math.random() * imageUrls.length);
const randomImageUrl = imageUrls[randomImageIndex];
const body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = `url(${randomImageUrl})`;
console.log(body);
<html>
<body>
</body>
</html>
Upvotes: 1
Reputation: 6644
Ideally you would provide an image already from the server-side, but if you're restricted to the client, this is one way of doing it:
// Your list of background images
const backgrounds = [
'https://picsum.photos/1024/768',
'https://picsum.photos/1024/768',
'https://picsum.photos/1024/768',
'https://picsum.photos/1024/768',
'https://picsum.photos/1024/768'
];
// Pick a random index in the list of images
const randomIndex = Math.floor(Math.random() * Math.floor(backgrounds.length));
// Select the random background image
const backgroundImage = backgrounds[randomIndex];
// Set the background image of the document root, in this case <html>
document.documentElement.style.backgroundImage = `url(${backgroundImage})`;
html {
background-repeat: no-repeat;
background-size: cover;
}
Upvotes: 2
Reputation: 2000
This should work
const images = ["https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500", "https://images.unsplash.com/photo-1546146477-15a587cd3fcb?ixlib=rb-1.2.1&w=1000&q=80", "https://cdn.pixabay.com/photo/2017/08/30/01/05/milky-way-2695569_960_720.jpg"];
//you can add as many image paths as you want
function generateRandomBackground() {
let randomImageURL = images[Math.floor(Math.random() * (images.length))];
console.log(randomImageURL);
document.body.style.backgroundImage= 'url('+randomImageURL+')';
}
document.body.onload = () => {
generateRandomBackground();
}
body {
background-size: cover;
background-repeat: no-repeat;
}
<body>
</body>
Hope this helps
Upvotes: 2