Clock Appender (prototype version)
by joplomacedo
HTML
<div id="clock">00:00</div>
<button id="start">Start Timer</button>
<button id="stop">Stop Timer</button>
<button id="reset">Reset Timer</button>
CSS
* {
box-sizing: border-box;
}
.dpNone {
display: none;
}
button {
vertical-align: top;
margin: 0;
cursor: pointer;
width: 150px;
height: 27px;
padding: 6px 4px 7px;
border: 0;
border-radius: 1px;
box-shadow: inset 0 0 0 1px rgba(0,0,0,0.18),
inset 0 2px rgba(255,255,255,0.3),
inset 0 -2px rgba(0,0,0,0.10);
font: bold 13px arial, helvetica;
color: #fff;
text-shadow: 0 1px rgba(0,0,0,0.3);
}
button:active {
box-shadow: inset 0 0 0 1px rgba(0,0,0,0.18),
inset 0 0 13px 1px rgba(0,0,0,0.18);
}
#start {
background-color: #91d159;
}
#stop {
background-color: #ce5c58;
}
#reset {
background-color: #b2aea2;
}
#clock {
display: inline-block;
width: 150px;
height: 27px;
padding: 2px 4px 3px;
border: 1px solid rgba(0,0,0,0.2);
font: 15px helveticaneue-light, helvetica, arial;
color: #333;
text-align: center;
}
JavaScript
(function($) {
var addClockTo = (function() {
var Clocky = function(node) {
this.node = node;
this.time = 0;
this.secs = 0;
this.minutes = 0;
this.clock_timeout = undefined;
};
Clocky.prototype = {
startClock: function() {
if (!this.clock_timeout) this.clock();
},
stopClock: function() {
if (this.clock_timeout) {
clearTimeout(this.clock_timeout);
this.time--;
this.clock_timeout = undefined;
}
},
resetClock: function() {
if (!this.clock_timeout) {
this.node.text("00:00");
this.time = 0;
}
},
clock: function() {
this.secs = this.time % 60;
this.minutes = (this.time - this.secs) / 60;
//prepend 0 if number is 1 digit long
if (this.secs < 10) this.secs = "0" + this.secs;
if (this.minutes < 10) this.minutes = "0" + this.minutes;
this.node.text(this.minutes + ":" + this.secs);
this.time++;
this.clock_timeout = setTimeout(this.clock.bind(this), 1000);
}
};
return function(node) {
var h = new Clocky(node);
node.startClock = function() {
h.startClock();
};
node.stopClock = function() {
h.stopClock();
};
node.resetClock = function() {
h.resetClock();
};
};
})();
var $start = $('#start'),
$stop = $('#stop').addClass('dpNone'),
$reset = $('#reset').addClass('dpNone'),
$clock = $('#clock');
addClockTo($clock);
$start.on('click', function() {
$clock.startClock();
...