Tap Counter
by Brian Duffey
HTML
<h3>Click 'start', and then click the grey square to count clicks</h3>
<label for="type">Tap Length:</label>
<select id="type" name="type">
<option value="10">10 Seconds</option>
<option value="20">10 and 20 Seconds</option>
</select>
<div id="counter">Seconds elapsed: 0</div>
<div id="count">0</div>
<div id="main">
<input id="start" type="button" value="Click to Start" />
</div>
<br />
<p># of clicks in 10 seconds: <span id="ten">-</span>
</p>
<p style="display:none;"># of clicks in 20 seconds: <span id="twenty">-</span>
</p>
CSS
div#main {
width:200px;
height:200px;
background-color:lightgrey;
}
div#count {
margin:0 0 10px 0;
}
input {
margin:50px 50px;
}
h3 {
text-align:center;
}
div#counter {
margin:5px 0;
visibility:hidden;
}
JavaScript
jQuery(function () {
jQuery('input#start').click(function () {
jQuery(this).hide();
jQuery('span#ten').text('-');
jQuery('span#twenty').text('-');
jQuery('div#counter').css('visibility', 'visible');
window.counter = setInterval(function () {
myCounter();
}, 1000);
jQuery('div#main').click(function () {
jQuery('div#count').text(parseInt(jQuery('div#count').text(), 10) + 1);
});
});
jQuery('select#type').change(function() {
if (jQuery(this).val() === '10') {
jQuery('span#twenty').parent('p').hide();
} else {
jQuery('span#twenty').parent('p').show();
}
});
});
function myCounter() {
var sec = jQuery('div#counter').text().split(':');
if (parseInt(sec[1], 10) === 10) {
jQuery('span#ten').text(jQuery('div#count').text());
if (parseInt(jQuery('select#type').val(), 10) === 10) {
window.clearInterval(counter);
alert('Time\'s up!');
reset();
return;
}
} else if (parseInt(sec[1], 10) === 20) {
jQuery('span#twenty').text(jQuery('div#count').text());
window.clearInterval(counter);
alert('Time\'s up!');
reset();
return;
}
jQuery('div#counter').text(sec[0] + ': ' + (parseInt(sec[1], 10) + 1));
}
function reset() {
jQuery('div#count').text('0');
jQuery('input#start').show();
jQuery('div#main').unbind('click');
jQuery('div#counter').text('Seconds elapsed: 0').css('visibility', 'hidden');
}