Search code examples
javascriptruby-on-railsaccessibilitykeycode

Spacebar (keycode 32) to act as Enter key except inside an input field


I'm working on adding accessibility to a program for hard-of-seeing users. For this, we are using the tab key to maneuver through the page. The user can then use the spacebar as the enter key, to open a link they are focused on, for example. I'm working on the spacebar to act in this manner at all times (using "e.preventDefault()"), except of course when inside an input field. I've written what makes logical sense to me, but does not work. Does anyone have any suggestions, please? This is what I have in a javascript file:

var textFieldEntry = document.querySelectorAll('input.field-input');
if (e.key == 'Space' || e.keyCode == 32) {
  if (e.target !== textFieldEntry) {
    e.preventDefault();
    e.target.click();
  };
}

Solution

  • not an answer, designed to show OP why his function doesn't work as intended and will be removed

    var textFieldEntry = document.querySelectorAll('input.field-input');
    $(document).on('keydown', function(e){
    if (e.key == 'Space' || e.keyCode == 32) {
      console.log("space pressed");
      console.log("e.target", e.target);
      console.log("textFieldEntry", textFieldEntry);
      if (e.target !== textFieldEntry) {
        e.preventDefault();
        e.target.click();
      };
    }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input class="field-input"/>
    <input class="field-input"/>
    <input class="field-input"/>