Skip to content

Instantly share code, notes, and snippets.

@fyrfli
Created March 27, 2022 06:56
Show Gist options
  • Save fyrfli/f257a621d29003379ed8a25c08e41ca2 to your computer and use it in GitHub Desktop.
Save fyrfli/f257a621d29003379ed8a25c08e41ca2 to your computer and use it in GitHub Desktop.
Working up to a calculator app
<div id="jscontainer" class="container">
<div class="result" id="jsresult"></div>
<input class="nos" type="button" value="1">
<input class="nos" type="button" value="2">
<input class="nos" type="button" value="3">
<input class="nos" type="button" value="4">
<input class="nos" type="button" value="5">
<input class="nos" type="button" value="6">
<input class="nos" type="button" value="7">
<input class="nos" type="button" value="8">
<input class="nos" type="button" value="9">
<input class="nos" type="button" value="0">
<input class="op" type="button" value="+">
<input class="op" type="button" value="-">
<input class="op" type="button" value="*">
<input class="op" type="button" value="/">
<input class="op" type="button" value="=">
</div>
window.onkeydown = function () {
// Also takes shift and alt, etc into considering.
const validKeys = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"+",
"-",
"=",
"*",
"/"
];
const numbKeys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
const opKeys = ["+", "-", "=", "*", "/"];
const clrKey = ["C", "c"];
if (validKeys.includes(event.key)) {
// 1. Display keys until + - * / = c/C pressed
// 2. When + - * / = c/C pressed: calc or clear screen
// 3. When = pressed, show result.
document.getElementById("jsresult").innerHTML =
"You typed: " + event.key;
} else {
alert("That key is not a number or operator");
}
};
jscontainer.onclick = function () {
document.getElementById("jsresult").innerHTML =
"You clicked: " + event.target.value;
};
.container {
width: fit-content;
margin: 4rem auto;
padding: 20px;
box-shadow: 0 2px 8px grey;
border-radius: 20px;
display: grid;
grid-template-columns: repeat(5, 65px);
grid-template-rows: repeat(3, 1fr);
gap: 10px;
}
input {
width: 65px;
height: 65px;
border-radius: 50%;
border: none;
font-size: 18px;
}
.result {
width: 350px;
height: 18px;
margin: auto;
background-color: darkgrey;
border: 1px inset grey;
padding: 10px;
grid-column: span 5;
border-radius: 8px;
font-size: 19px;
text-align: right;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment