Add an eventListener on the document and listen for a keydown
event. On keydown
check the event.key
entry and if it is set to the desired key, run the desired code; add, subtract or reset your value. A switch conditional may be better suited for this application as well.
let add = document.getElementById("increment");
let remove = document.getElementById("decrement");
let reset = document.getElementById("reset");
let int = document.getElementById("number");
let integer = 0;
document.addEventListener('keydown', (e) => {
if (e.key === "ArrowUp") {
integer++;
} else if (e.key === "ArrowDown") {
integer--;
} else if (e.key === "Enter") {
integer = 0;
}
int.textContent = integer;
});
add.addEventListener('click', function() {
integer += 1;
int.innerHTML = integer
})
remove.addEventListener('click', function() {
integer -= 1;
int.innerHTML = integer
})
reset.addEventListener('click', function() {
integer = 0;
int.innerHTML = integer
})
@charset "utf-8";
#container {
width: 246px;
height: 187px;
background-color: #F7CF5B;
padding-top: 4px;
padding-left: 25px;
border-radius: 20px;
border: 4px solid #09AA20;
margin-top: 20px;
margin-left: 10px;
}
#number {
background-color: #19A709;
width: 77%;
border-radius: 10px;
border: 3px solid #FF2600;
padding-top: 5px;
padding-left: 10px;
font-size: 60px;
text-align: left;
color: #FFFFFF;
margin-left: 8px;
}
#title {
color: #FF0000;
font-size: 33px;
font-style: normal;
font-weight: bold;
margin-left: 8px;
padding-bottom: 10px;
}
#increment {
width: 60px;
height: 30px;
padding-top: 1px;
padding-right: 1px;
padding-bottom: 1px;
padding-left: 1px;
margin-top: 11px;
margin-left: 9px;
font-size: 19px;
color: #FFFFFF;
background-color: #09AA20;
text-align: center;
}
#decrement {
width: 60px;
height: 30px;
padding-top: 1px;
padding-right: 1px;
padding-bottom: 1px;
padding-left: 1px;
margin-top: 11px;
margin-left: 9px;
font-size: 19px;
color: #FFFFFF;
background-color: #0226F9;
}
#reset {
width: 60px;
height: 30px;
padding-top: 1px;
padding-right: 1px;
padding-bottom: 1px;
padding-left: 1px;
margin-top: 11px;
margin-left: 9px;
font-size: 19px;
color: #FFFFFF;
background-color: #252525;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tally Counter 1.0</title>
<link href="CSS/counter.css" rel="stylesheet" type="text/css">
<style type="text/css">
body {
background-color: #7B1A1A;
}
</style>
</head>
<body>
<div id="container">
<div id="title">Tally Counter</div>
<div id="number">0</div>
<button id="increment">+1</button>
<button id="decrement">-1</button>
<button id="reset">Reset</button>
<script src="scripts/main.js"></script>
</div>
</body>
</html>
CLICK HERE to find out more related problems solutions.