Created
June 20, 2019 19:30
-
-
Save thatdevgirl/61ad6a7ece83d4a2515f5ce6d2110e00 to your computer and use it in GitHub Desktop.
Function that handles focus when user navigates through a site using their keyboard. Prevents the focus from getting stuck, which can sometimes happen with carousels.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function handleTabFocus(e) { | |
let focus = document.activeElement, | |
newFocus; | |
$(document).keyup(function(e) { | |
const code = e.keyCode || e.which; | |
// If the tab key is pressed: | |
if (code === 9) { | |
// Determine which element has focus now. | |
newFocus = document.activeElement; | |
// If the focus did not change, change it manually. | |
if (focus == newFocus) { | |
// Get a list of all focusable, visible elements. | |
let focusableEls = $("*:focusable:visible"); | |
// Get the index of the element that currently has focus. | |
let index = focusableEls.index(focus); | |
// Determine the index of the next item to have focus based on whether user is going forward or back. | |
let newIndex = (e.shiftKey) ? index-1 : index+1; | |
// Put the focus on the next element in the list. | |
focusableEls[newIndex].focus(); | |
} | |
// Save the element that currently has focus. | |
focus = document.activeElement; | |
} | |
}); | |
} | |
handleTabFocus(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm on the Making WordPress and WPCampus slacks and also on Discord. Feel free to email me too at [email protected]
Some key accessibility points I'll make here, though:
<ul>
). The forward/back buttons are maybe a form? Slide indicators are the navigation (e.g.<nav>
) of your carousel.Let's definitely chat more! I think seeing your code too will make a conversation more productive.