Page Widget How to - Create random css background








Question

We would like to know how to create random css background.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
body, html {<!--from   www  .j a  va 2  s . c om-->
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  border: none;
}

body {
  background-position: right bottom;
  background-repeat: no-repeat;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var imgArray = [
    "http://placehold.it/200x200",
    "http://placehold.it/201x201",
    "http://placehold.it/202x202"
];
function ranNum(){
    return Math.floor(Math.random()*imgArray.length); 
}
document.body.style.backgroundImage = "url(" + imgArray[ranNum()] + ")"; 
}//]]>  
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: