Created
October 7, 2012 08:19
-
-
Save santosh/3847513 to your computer and use it in GitHub Desktop.
JavaScript: Method #1: Randomize elements on a page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html dir="ltr" lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> | |
<meta name="viewport" content="width=device-width"> | |
<title>Randomize Element</title> | |
<style type="text/css" media="screen">/* mininal style {{ */ | |
html, body { height: 100%; overflow: hidden;} | |
.rand { | |
position: absolute; | |
width: 48px; | |
height: 48px; | |
} | |
#random1 { | |
background: red; | |
} | |
#random2 { | |
background: green | |
} | |
#random3 { | |
background: lightblue; | |
} | |
#random4 { | |
background: magenta; | |
} | |
/* }} */</style> | |
</head> | |
<body> | |
<div id="random1" class='rand'> Foo </div> | |
<div id="random2" class='rand'> Bar </div> | |
<div id="random3" class='rand'> Far </div> | |
<div id="random4" class='rand'> Boo </div> | |
<script type="text/javascript" charset="utf-8"> // randomizer script {{ | |
var imgs = document.querySelectorAll('.rand'), | |
len = imgs.length, | |
s = (window.getComputedStyle)?getComputedStyle(document.body):document.body.currentStyle, | |
// subtract the width/ height of images | |
w = parseInt(s.width.split('px')[0], 10) - 48, | |
h = parseInt(s.height.split('px')[0], 10) - 48; | |
console.log(len); | |
for(var i = 0; i < len; i++) { | |
imgs[i].style.top = Math.floor(Math.random() * h) + 'px'; | |
imgs[i].style.left = Math.floor(Math.random() * w) + 'px'; | |
} | |
//}} </script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment