15 minute challenge
by alexb
HTML
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
<div id="z"></div>
CSS
div {
background: cornflowerblue;
border: 2px solid blue;
border-radius: 50%;
display: inline-block;
height: 50px;
position: absolute;
width: 50px;
}
#z {
background: red;
border: none;
height: 30px;
margin: 10px;
width: 30px;
z-index: -1;
}
p {
margin-top: 200px;
width: 460px;
text-align: center;
font-size: 48px;
}
JavaScript
$.fn.x = function(x) {
if (x == null) {
return this.position().left;
}
else {
this.css('left', x);
}
}
$.fn.y = function(y) {
if (y == null) {
return this.position().top;
}
else {
this.css('top', y);
}
}
$.fn.xy = function(x, y) {
if (x == null && y == null)
return [this.x(), this.y()];
this.x(x);
this.y(y);
}
function right() {
b.animate({ top: 30 });
$('body').append('<p>Well done!</p>');
}
function wrong() {
alert('Nope. Try again!');
}
var a = $('#a'),
b = $('#b'),
c = $('#c'),
abc = $('#a, #b, #c'),
z = $('#z');
a.xy(100, 30);
b.xy(200, 30);
c.xy(300, 30);
z.xy(200, 100);
$(function() {
setTimeout(function() {
abc.animate({ top: '+=70' }, 'slow').promise().done(function() {
z.hide();
var swap = function() {
var rand = Math.floor(Math.random() * 2.999999),
swap = abc.not(abc.eq(rand)),
s0 = swap.eq(0),
s1 = swap.eq(1),
x0 = s0.x(),
x1 = s1.x();
s0.animate({ left: x1 }, 'slow');
return s1.animate({ left: x0 }, 'slow').promise();
}
var count = 0;
function doSwap() {
swap().done(function() {
count++;
if (count < 10) {
doSwap();
}
else {
z.x(b.x());
z.show();
a.click(wrong);
b.click(right);
c.click(wrong);
}
});
}
doSwap();
});
}, 2000);
});