Skip to content

Instantly share code, notes, and snippets.

@shiftyp
Last active August 29, 2015 14:17
Show Gist options
  • Save shiftyp/8ea22768d9da832a1bfd to your computer and use it in GitHub Desktop.
Save shiftyp/8ea22768d9da832a1bfd to your computer and use it in GitHub Desktop.
jQuery Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Example</title>
<link href="./style.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script src="./index.js" type="text/javascript"></script>
</head>
<body>
<div id="container">
<!-- This is empty, but we'll add some elements -->
</div>
</body>
</html>
var clickTargetTimeout = null;
function getRandomColor() {
var colors = [
'#195073',
'#F2F2F2',
'#F2CB05',
'#F29F05',
'#BF5B04'
];
return colors[Math.floor(Math.random() * colors.length)];
}
function addClickTarget(container) {
var target = $(document.createElement('div')).appendTo(container);
target
.addClass('click-target')
generateClickTargetCSS(container, target);
}
function generateClickTargetCSS(container, target) {
var bounds = {
width: container.width() - target.width(),
height: container.height() - target.height()
};
target.css({
top: bounds.height * Math.random(),
left: bounds.width * Math.random(),
backgroundColor: getRandomColor()
});
}
function addClickTargetTimeout(container) {
var addClickTargetDelay = 2000;
clickTargetTimeout = setTimeout(function() {
addClickTarget(container);
addClickTargetTimeout(container);
}, Math.random() * addClickTargetDelay);
}
function removeClickTarget(e) {
$(this).remove();
// When you delegate events, jQuery adds a property to the
// event object that equals the container element. So
// e.delegateTarget is #container
if (!$(e.delegateTarget).children('.click-target').length) {
alert('You win! good job!');
clearTimeout(clickTargetTimeout);
}
}
$(function() {
var container = $('#container');
for (var i = 0; i < 10; i++) {
addClickTarget(container);
}
container.on('click', '.click-target', removeClickTarget);
addClickTargetTimeout(container);
});
#container {
position: relative;
width: 500px;
height: 300px;
margin: 10px auto;
border: 1px solid #0B2433;
}
.click-target {
position: absolute;
border-radius: 50%;
height: 30px;
width: 30px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment