Created
October 7, 2012 08:31
-
-
Save santosh/3847532 to your computer and use it in GitHub Desktop.
JavaScript: Method #2: Randomize elements on a page
This file contains hidden or 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> Randomise Element's Position </title> | |
<style type="text/css" media="screen"> | |
.randomizeme { | |
position:absolute; | |
display:block; | |
width:50px; | |
height:50px; | |
} | |
#id1 { | |
background: red; | |
} | |
#id2 { | |
background: green; | |
} | |
#id3 { | |
background: lightblue; | |
} | |
#id4 { | |
background: magenta; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="id1" class='randomizeme'> Foo </div> | |
<div id="id2" class='randomizeme'> Bar </div> | |
<div id="id3" class='randomizeme'> Boo </div> | |
<div id="id4" class='randomizeme'> Far </div> | |
<script type="text/javascript" charset="utf-8"> // {{ | |
window.onload = function() { | |
var elements = document.querySelectorAll(".randomizeme"); | |
for (var i in elements) { | |
var top = Math.floor(Math.random() * 100); | |
var left = Math.floor(Math.random() * 100); | |
var e = elements[i]; | |
e.style.top = top + '%'; | |
e.style.left = left + '%'; | |
if (top > 50) { | |
console.log(e); | |
e.style.marginTop = (-1 * e.height) + 'px'; | |
} | |
if (left > 50) { | |
e.style.marginLeft = (-1 * e.width) + 'px'; | |
} | |
} | |
}; | |
// }} </script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment