Skip to content

Instantly share code, notes, and snippets.

@funilrys
Created April 4, 2017 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save funilrys/24ee80605a31cbeda33b720d1848596e to your computer and use it in GitHub Desktop.
Save funilrys/24ee80605a31cbeda33b720d1848596e to your computer and use it in GitHub Desktop.
How to change background randomly
/**
* Return a list of URL
* @returns {array}
*/
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;
}
/**
* 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));
}
/**
* Get a random url from backgrounds
* @returns {str}
*/
function getBackground() {
var numberOfImages = backgrounds().length,
uniqueNumber = randomNumber(numberOfImages);
return backgrounds()[uniqueNumber];
}
/**
* 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";
}
// On load, we show the background on screen
window.onload = showBackground();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment