How to get random background (in JavaScript)? That's what I do here!
Functions
In order to be more efficient I choose to write some Functions.
backgrounds()
We need a function which return a list of link (or filename) to use as background.
/**
* Return a list of URL
*/
function backgrounds() {
// We create a variable
var imageURLs = [
// We assign in an array the list of URL/filename we want as background
"https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-301322.jpg",
"https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-103541.jpg",
"https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-279000.jpg",
"https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-106689.jpg",
"https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-365847.jpg",
"https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-284161.jpg"
];
// We return the created variable
return imageURLs;
}
randomNumber()
We need a function that return a random in range [0-x]
where x
is the length of backgrounds()
.
/**
* Return a random number in range [0-x] where x is the length of backgrounds
* @param {int} max
* @returns {int}
*/
function randomNumber(max) {
return Math.floor((Math.random() * max));
}
getBackground()
We need a function that return a background from backgrounds()
with randomNumber()
as index.
/**
* Get a random url from backgrounds
* @returns {str}
*/
function getBackground() {
var numberOfImages = backgrounds().length,
uniqueNumber = randomNumber(numberOfImages);
return backgrounds()[uniqueNumber];
}
showBackground()
we need a function that return a well formatted css for the background.
/**
* show background on screen
* @returns {DOM}
*/
function showBackground() {
document.body.style.backgroundImage = "url('" + getBackground() + "')";
document.body.style.backgroundPosition = "center center";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundAttachment = "fixed";
}
Load all on page loading
// On load, we show the background on screen
window.onload = showBackground();
Final script
Known issue
This script doesn't work on safari.