Created
August 31, 2012 17:04
-
-
Save jpetto/3555903 to your computer and use it in GitHub Desktop.
DOM Demo - Whack-a-mole
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> | |
<head> | |
<title>Whack-a-mole</title> | |
<style type="text/css"> | |
#field { | |
width: 500px; | |
height: 500px; | |
position: relative; | |
background: #ccc; | |
} | |
#mole { | |
width: 50px; | |
height: 50px; | |
position: absolute; | |
top: 0px; | |
left: 0px; | |
background: #333; | |
} | |
#mole div { | |
display: none; | |
font-size: 40px; | |
text-align: center; | |
} | |
#mole.captured { | |
background: #f1f1f1; | |
} | |
#mole.captured div { display: block; } | |
</style> | |
</head> | |
<body> | |
<section id="field"> | |
<div id="mole"><div>!</div></div> | |
</section> | |
<script type="text/javascript"> | |
var max_x = 450; // max x value is width of field (500) - width of mole (50) | |
var max_y = 450; // same for y value | |
var mole = document.querySelector("#mole"); | |
var mole_captured = false; | |
var jump = function() { | |
var random_x, random_y, new_x, new_y; | |
if (!mole_captured) { | |
random_x = Math.random() * max_x; | |
random_y = Math.random() * max_y; | |
new_x = Math.floor(random_x + 1); | |
new_y = Math.floor(random_y + 1); | |
mole.setAttribute("style", "top: " + new_y + "px; left: " + new_x + "px"); | |
setTimeout(function() { | |
jump(); | |
}, 700); | |
} | |
}; | |
// start game as soon as page loads | |
jump(); | |
// when you click on the mole, stop the game | |
mole.addEventListener('click', function(e) { | |
mole_captured = true; | |
mole.setAttribute('class', 'captured'); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment