Search code examples
javascriptkeypressevent-listener

Applying keypress listener to all subelements


Supposing that I have some nested html elements that look something like this:

<div class='container'>
  <p>content</p>
  <p>in enough different elements</p>
  <p>that making listeners</p>
  <p>for all of them</p>
  <p>would be a huge pain</p>
<div>

Is it possible to write a javascript listener tied to the container div that responds to a keyDown event while any of its child elements are in focus?


Solution

  • The keydown event supports event bubbling, so you can just add the handler to the container element like

    document.querySelectorAll('.container')[0].addEventListener('keydown', function(e) {
      console.log('keypressed', this, e);
      //e.target will refer to the actual event target
    
      log('down in `' + e.target.innerHTML + '` with keycode: ' + (e.keyCode))
    })
    
    function log(msg) {
      document.querySelector('#log').innerHTML = msg;
    }
    <div class='container'>
      <p tabindex="1">content</p>
      <p tabindex="1">in enough different elements</p>
      <p tabindex="1">that making listeners</p>
      <p tabindex="1">for all of them</p>
      <p tabindex="1">would be a huge pain</p>
    </div>
    <div id="log"></div>