/**
* a calculator function used to create instances of simple math calculators
*/
var Calculator = function (el) {
var input, buttons, input1, input2, operator;
// responsible for getting elements and kicking off events
function init(el) {
if (el) {
el = $( el );
} else {
el = $('#calculator');
if ( el.length < 1 ) {
return null;
}
}
// get our input and our buttons
input = el.find( '.calculator-input' );
buttons = el.find( 'a.btn' );
events();
}
function events() {
// block user from entering text in input box
input.on('keydown', function (e) {
// prevent default action
e.preventDefault();
});
// when a button is clicked, cache it and it's value, delegate
buttons.on('click', function(e) {
var target = $( this );
var val = target.text();
delegate( target, val );
// prevent default action
e.preventDefault();
});
}
function delegate ( target, val ) {
// check to see if we are working with an operator
if ( target.hasClass( 'operator' ) ) {
// see if the first input is set, if not set it
if ( !input1 ) {
input1 = input.val();
}
// if operator is set that means we need to run a calculation
if ( operator ) {
// first set input2
input2 = input.val().split(operator)[1];
// run calculation
calculate();
}
// set the operator and update the display
operator = val;
updateDisplay(val);
//...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.