Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save paulorodriguesxv/e5c667f5d2e5ee036b8e to your computer and use it in GitHub Desktop.
Save paulorodriguesxv/e5c667f5d2e5ee036b8e to your computer and use it in GitHub Desktop.
Zipline: Build a JavaScript Calculator
<div id="calculator">
<div class="screen">0</div>
<div id="keypad">
<ul>
<li class="symbolTop" id="clear">AC</li>
<li class="symbolTop">+/-</li>
<li class="symbolTop">%</li>
<li class="symbol">/</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li class="symbol">x</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li class="symbol">-</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li class="symbol">+</li>
<li class="extend">0</li>
<li>.</li>
<li class="symbol">=</li>
</ul>
</div>
</div>
var btns = document.getElementById('keypad');
var entries = [];
var total = 0;
var temp = '';
$("li").on('click', function() {
var val = $(this).text();
if (!isNaN(val) || val === '.') {
temp += val;
$("#clear").text("C");
$(".screen").text(temp.substring(0,10));
} else if (val === 'AC') {
entries = [];
temp = '';
total = 0;
$(".screen").text('0')
} else if (val === 'C') {
temp = '';
$("#clear").text("AC");
$(".screen").text('0')
} else if (val === 'x') {
entries.push(temp);
entries.push('*');
temp = '';
// Change divide symbol to work with eval
} else if (val === '÷') {
entries.push(temp);
entries.push('/');
temp = '';
} else if (val === '=') {
entries.push(temp);
console.log(entries);
var newTotal = eval(entries.join('').substring(0, 10))
$(".screen").text(newTotal);
entries = [];
temp = '';
} else if (val === '%') {
$(".screen").text("TODO :-)");
entries = [];
temp = '';
} else if (val === '+/-') {
temp = temp * (-1);
$("#clear").text("C");
$(".screen").text(temp);
} else {
entries.push(temp);
entries.push(val);
temp = '';
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
body {
background: #000;
}
#calculator {
width: 300px;
background: #505050;
margin: 10px auto;
font-family: Arial;
overflow: hidden;
}
.screen {
height: 70px;
width: 95%;
color: #F0F0F0;
font-size: 50px;
line-height: 70px;
text-align: right;
overflow: hidden;
padding: 5px;
}
#keypad li {
list-style-type: none;
width: 25%;
height: 70px;
background: #E0E0E0;
float: left;
text-align: center;
line-height: 70px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
border: 1px solid #000000;
}
#keypad .extend {
width: 50%;
}
#keypad .symbol {
background: #fba01f;
color: white;
font-size: 30px;
border-right: none;
}
#keypad .symbolTop {
background: #B8B8B8;
color: white;
font-size: 30px;
}
#keypad li:active {
outline: 0;
background: #AAAAAA;
}
.active {
-moz-box-shadow: inset 0 0 5px #000000;
-webkit-box-shadow: inset 0 0 5px #000000;
box-shadow: inset 0 0 5px #000000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment