Skip to content

Instantly share code, notes, and snippets.

@erhangundogan
Created February 11, 2014 08:05
Show Gist options
  • Select an option

  • Save erhangundogan/8930874 to your computer and use it in GitHub Desktop.

Select an option

Save erhangundogan/8930874 to your computer and use it in GitHub Desktop.
raw calculator
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
input[type=button] {
width: 40px;
height: 40px;
margin: 5px;
}
input[type=text] {
margin-top: 5px;
height: 32px;
}
</style>
</head>
<body>
<script>
function createButton(context, text, func) {
var button = document.createElement("input");
button.type = "button";
button.value = text;
button.onclick = func;
context.appendChild(button);
}
window.onload = function() {
var commands = ['1','2','3','4','5','6','7','8','9','0','+','-','*','/','='],
container = document.createDocumentFragment(),
inputResult = '';
for (var i = 0; i < commands.length; i++) {
if (i % 3 === 0) {
container.appendChild(document.createElement('br'));
}
createButton(container, commands[i], function(event){
var clicked = event.currentTarget.value,
item = document.getElementById('result');
if (clicked === '=') {
inputResult = item.value = eval(item.value);
} else {
inputResult += clicked;
item.value = inputResult;
}
});
}
container.appendChild(document.createElement('br'));
var input = document.createElement('input');
input.type = 'text';
input.id = 'result';
container.appendChild(input);
document.body.appendChild(container);
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment