Skip to content

Instantly share code, notes, and snippets.

@spencermathews
Created February 5, 2016 00:52
Show Gist options
  • Save spencermathews/39108c583161becc4c08 to your computer and use it in GitHub Desktop.
Save spencermathews/39108c583161becc4c08 to your computer and use it in GitHub Desktop.
image demo random
$(function() {
console.log("ready");
//create array to hold images
var treeChico = ["http://www.redrocketmedia.com/des157/images/tree.png", "http://www.redrocketmedia.com/des157/images/tree2.png", "http://www.redrocketmedia.com/des157/images/tree3.jpg", "http://www.redrocketmedia.com/des157/images/sign.png", "http://www.redrocketmedia.com/des157/images/leaves.png", "http://www.redrocketmedia.com/des157/images/Penelope.png", "http://www.redrocketmedia.com/des157/images/sky.jpg"];
//create an empty array to hold the images as objects
var imgs = [];
//traverse the array for preloading images
for (var i = 0; i < treeChico.length; i++) {
//create a new image object at position of i in the array
//this is the magic that makes the image download...putting it into an object
imgs[i] = new Image();
//assign the src for each new image
imgs[i].src = treeChico[i];
}
//call to getNewPic
getNewPic();
//love this!
$(window).resize(getNewPic);
function getNewPic() {
console.log("new pic");
//create a random number between 0 and length of treeChico array
//Math.floor truncates the decimal of the number
var myRandom = Math.floor(Math.random() * treeChico.length);
//change the image source
$('body').css('backgroundImage', 'url(' + treeChico[myRandom] + ')');
}
//close jQuery ready function
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
* {
margin:0px;
padding:0px;
}
body {
background-color:#222;
background-image:url(http://www.redrocketmedia.com/des157/images/leaves.png);
background-size: 90%;
background-repeat: no-repeat;
overflow:hidden;
}
section {width:100%; height:100%; background-color:orange}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment