Skip to main content

Register Key Press Event On Multiple Elements With Vanilla Javascript

By February 14, 2017Accessibility, Blog, Javascript
Allure Web Solutions Code Snippet

This little snippet shows you how to use vanilla JavaScript to select multiple matched elements and assign to them an event handler that reads a particular key press and then performs an action.

Why is this useful? Well, it’s probably most useful for accessibility. Imagine you are using a screen reader and navigating the website using your keyboard. To navigate the website with a keyboard, you would mainly press the TAB key. So you’re on the website and you open a main navigation menu tab and shows the dropdown. Then you tab through all of the dropdown links until you reach the next main menu tab. At this point, we would want to close the dropdown menu automatically. This is what the below code is showing.

 

The Code

// Select which elements you want to target
// They must be "focusable" elements such as links or form inputs
var matchedElements = document.querySelectorAll('li > a');

// Loop through all of the matched elements
for (var i = 0; i < matchedElements.length; i++) {
  // Add event listener that binds the key handler
  if (matchedElements[i].addEventListener) {
    matchedElements[i].addEventListener('keydown', accessibleKeyHandler, false);
  } 
  // Same thing for IE
  else if (matchedElements[i].attachEvent) {
    matchedElements[i].attachEvent('onkeydown', accessibleKeyHandler);
  }
}

// Key handler function
function accessibleKeyHandler(e) {
  // Set which key you want to target
  // Key 9 is the tab key which is important for accessibility
  var key = 9;
  if (e.keyCode === key) {
    // Do something here

    return false;
  }
}

 

Example

Press the tab key to see the script in action

allure

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017