Search code examples
javascriptbuttoncounterkeypress

Need a keypress button with a counter


I'm working on an interactive voting booth and I need to have buttons that count but can also be triggered by a,b,c,etc keys. I have the counting js figured out, but I'm having a hard time getting the keypress to work.

Here's

var totala = 0;

document.getElementById('add1a').onclick = add1a;

function add1a() {
  totala = totala + 1;
  document.getElementById('resulta').innerHTML = totala;
}

var totalb = 0;

document.getElementById('add1b').onclick = add1b;

function add1b() {
  totalb = totalb + 1;
  document.getElementById('resultb').innerHTML = totalb;
}

var totalc = 0;

document.getElementById('add1c').onclick = add1c;

function add1c() {
  totalc = totalc + 1;
  document.getElementById('resultc').innerHTML = totalc;
}
#add1a {
    background-image: url( 'http://i59.tinypic.com/fx428h.jpg' );
    background-size: 100px 130px;
    height: 134px;  
    width: 104px;
}

#add1b {
    background-image: url( 'http://i59.tinypic.com/fx428h.jpg' );
    background-size: 100px 130px;
    height: 134px;  
    width: 104px;
}

#add1c {
    background-image: url( 'http://i59.tinypic.com/fx428h.jpg' );
    background-size: 100px 130px;
    height: 134px;  
    width: 104px;
}
<button id="add1a"></button>

<h1 id="resulta">0</h1>

<button id="add1b"></button>

<h1 id="resultb">0</h1>

<button id="add1c"></button>

<h1 id="resultc">0</h1>

the js:


Solution

  • JS provides keydown, keypress, and keyup events that you can use to detect keypresses. You can attach a keypress event handler to the whole page.

    For example:

    document.onkeypress = function (keypressEvent) {
      if (keypressEvent.key === 'a') {
        add1a();
      } else if (keypressEvent.key === 'b') {
        add1b();
      }
    };