Skip to content

Instantly share code, notes, and snippets.

@AntonTrollback
Last active March 7, 2016 15:53
Show Gist options
  • Save AntonTrollback/5135512 to your computer and use it in GitHub Desktop.
Save AntonTrollback/5135512 to your computer and use it in GitHub Desktop.
Helper for styling tabbed focus states: html.tabbing a:focus { }
a {
color: rebeccapurple;
text-decoration: none;
outline: 0;
}
a:hover,
a:active {
color: rebeccapurple;
text-decoration: underline;
}
html.tabbing a:focus {
outline: 2px solid;
text-decoration: none;
}
$(function() {
var $root = $('html');
var tabbing, code;
$(document).on('mousedown keydown', function (e) {
if (e.type === 'mousedown') {
tabbing = false;
return;
}
code = e.keyCode ? e.keyCode : e.which;
if (code == 9) {
tabbing = true;
}
});
$('a, button, input[type="submit"]').on('focus', function (e) {
$root.toggleClass('tabbing', tabbing);
});
});
@jenshedqvist
Copy link

I think there's a couple of things things to consider:

The Assuming: Check for some specific user behaviour, "the user presses tab 3 times in a row and/or puts focus on elements in the natural tabbing order (siblings maybe)". Instead of relying on tab key, the "track focus" pattern might be more robust.

The State: You could either treat this as a "mode" that is then set for entire stay, either in memory (until page relad) or maybe localstorage/cookie user state. But then again a user might use keyboard for a while then switch to some other device so you need to change the state.

The Class Pattern: Global state classes could take a User-centric approach User-is-tabbing, User-is-usingKeybard or just describe the state body.has-enhancedKeyboardFocus.

@AntonTrollback
Copy link
Author

Using it like this, tabbing never felt better ^.^

/**
 * Set a more prominent focus state when navigating using the keyboard
 */

body[data-focus-source] :focus {
    outline: none !important;
}

body[data-focus-source="key"] :focus {
    outline: 2px solid red !important;
}

/* Focus states for input and textarea elements is styled using borders */

body[data-focus-source="key"] :matches([tabindex="-1"]:focus, input:focus, textarea:focus) {
    outline: none !important;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment