Sam St Aubyn
Sam St Aubyn

Reputation: 157

Integrate keypress events into jQuery functions for accessibility

I'm looking to optimise my jQuery functions on a recently built site for accessibility, for instance quite a few functions I used either have a hover or mouseover event as the main event listener, but to make these sections fully accessibly via keyboard ideally they need to have an keypress/keyup trigger also.

I've seen a few examples of people using keypress then wrapping the function in an if statement to match it to the enter key, but this will then disable any other trigger.

Does anyone have any ideas of how I can integrate the keypress into my simple mouseover event below for example:

$('.insight-featured').on('mouseover', function() {
  $(this).parent().next().children('.hover-frame').css({"opacity" : '1', "scale" : "1"})
})

Upvotes: 0

Views: 66

Answers (1)

OliverRadini
OliverRadini

Reputation: 6467

If you're sticking to jquery, you can handle it by just having a single event handler:

function handleTheThing (e) {
  if (e.keyCode !== undefined && e.keyCode !== 13) {
    return;
  }

  $(this).css({ color: "red" });
}

$("#test").on("mouseover", handleTheThing);
$("#test").on("keydown", handleTheThing);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="test">Here is a thing</button>

Upvotes: 0

Related Questions