0

I have a question. I have made a small site in HTML and vanilla JS to act as a counter. It is working fine, but I wanted to add a function that would allow the user to add or subtract 1 from the counter by pressing "+" or "-", in the numpad or not.

What is the easiest way to do this in vanilla JS?

RobSp1derp1g
  • 63
  • 1
  • 9

3 Answers3

1

Sure, just attach to the keyup events and increment or decrement the value when the proper key is pressed.

var value = 0;


document.addEventListener("DOMContentLoaded", function(event) {
    document.querySelector(".valueHolder").innerHTML = value;
  
 });

document.addEventListener("keyup", function(event) {
  
  if (event.which == "187" || event.which == "107") { // + key
    value++;
  }

  if (event.which == "189" || event.which == "109") { // - key
    value--;
  }

  
  document.querySelector(".valueHolder").innerHTML = value;
    
  
console.log(event.which);
});
<div class="valueHolder"></div>
nixkuroi
  • 2,259
  • 1
  • 19
  • 25
0

You will want to add an event listener on the document

document.addEventListener('keydown', myFunction);

function myFunction(e) {
    var keyCode = e.keyCode();
    ...
}

You'll want to look up the keycodes for the keys you will be using (+ and -) and compare that value to keyCode. Then use a conditional to execute your adding or subtracting.

Jeoff
  • 99
  • 5
0

You would create an event handler, which would add or subtract from a global variable based on the key pressed, like this:

window.counter=0;

function key(ev){
  if(ev.keycode==107) window.counter++;
  if(ev.keycode==109) window.counter--;
}

document.onkeypress = key;
Leo Wilson
  • 503
  • 1
  • 5
  • 16