Search code examples
javascripteventsonkeydown

How can I make an output to print +1 every time I do an onkeydown Event in javascript?


What I need is to make an onkeydown Event that when I press the key m, it will print a +1 in the output

the output in the html is:

<h1 id="moreNum">how many times have you pressed the "m": 0</h1>

and when I type m, it will print this: how many times have you pressed the "m": 1

if I click it again it will print: how many times have you pressed the "m": 2

and so on


Solution

  • You can addEventLisetner and increment the count only if the key pressed is m using key provided by the event object.

    const h1 = document.querySelector("#moreNum");
    let count = 0;
    
    function setText(times) {
      h1.textContent = `how many times have you pressed the "m": ${times}`
    }
    
    function logKey(e) {
      if (e.key === 'm') {
        ++count;
        setText(count);
      }
    
    }
    
    document.addEventListener('keydown', logKey);
    <h1 id="moreNum">how many times have you pressed the "m": 0</h1>