Reputation: 6158
Started a little project yesterday to make a calculator. I think it's fully working but I want to go a step further and add keyboard input (like you can on factory default OS calculators)
I have found an answer on here but it was for C#.
So:
How in JavaScript can I add keyboard input? This would include 0-9, all operators, "C" to clear and "delete"/"esc" to remove last entry.
Ideally I would like the css hover effect (darker shade) I did to happen
when clicking on the key too.
You can view the start here: http://codepen.io/apswak/pen/RapEqp
index.html
<div id="calculator">
<div id="screen">
<div id="calc">0</div>
<div id="result">0</div>
</div>
<button class="value">1</button><button class="value">2</button><button class="value">3</button><button class="value">+</button><button class="value">4</button><button class="value">5</button><button class="value">6</button><button class="value">-</button><button class="value">7</button><button class="value">8</button><button class="value">9</button><button class="value">*</button><button class="value">.</button><button class="value">0</button><button class="CE"> ←</button><button class="value">/</button><button class="equals">=</button><button class="C">C</button>
</div>
script.js
$(document).ready(function() {
var string = "";
/* Calculator input string */
$(".value").click(function() {
string += $(this).text();
$("#calc").text(string);
});
/* Clear all */
$(".C").click(function() {
string = "";
$("#calc, #result").text("0");
});
/* Clear last entry */
$(".CE").click(function() {
string = string.slice(0, string.length - 1);
$("#calc").text(string);
});
/* Show result */
$(".equals").click(function() {
$("#result").text(eval(string));
});
});
Upvotes: 2
Views: 8460
Reputation: 8537
Here's an example with keypress function on your codePen example :
http://codepen.io/anon/pen/WwjNao
document.onkeypress = function (e) {
keyPressed = String.fromCharCode(e.which);
if($("#calc").length > 0){
$("#calc").append(keyPressed);
}else{
$("#calc").text(keyPressed);
}
};
It's an hint, I will not give you all the code ;)
Upvotes: 6
Reputation: 467
I've started you off with some basic numbers in a copy of your code pen
You have to listen for a keypress and match the key (event.which) to the event it should trigger.
$(document).keypress(function(event){
console.log(event.which);
//0
if(event.which == 48){
string += 0;
$("#calc").text(string);
}
});
http://codepen.io/anon/pen/LNyYJM
Also if you do 0123+5 it says it equals 88 so you may want to make note of that as a bug.
Upvotes: 4
Reputation: 191
You could use keypress https://api.jquery.com/keypress/ and listen to which key is being pressed.
Keycodes: https://css-tricks.com/snippets/javascript/javascript-keycodes/
$( "#target" ).keypress(function( event ) {
if ( event.which == 48 ) {
// Return #0
}
if ( event.which == 49 ) {
// Return #1
}
// and so on...
});
Upvotes: 2