loading...
Cover image for Never forget the keyboard warriors

Never forget the keyboard warriors

rossangus profile image Ross Angus ・2 min read

I was polishing a site today and checking how it worked when using the keyboard to navigate when I noticed something: at certain points, the focus disappeared. Sometimes, this was because it got swallowed by tooltips or navigation bars (which I've since updated so they fly open). But even after this, the focus still went AWOL.

Then I remembered that I'd inherited a form where the manual submit button was hidden with JavaScript, but which auto-submits, when the user changes a select box.

I'd used the old trick of getting JavaScript to add a js class to the body, then used a data-js="hidden" attribute on elements I wanted to scoot out of the way. It's a variation of the old sr-only class:

.sr-only, .js [data-js="hidden"] {
  border: 0;
  clip: rect(0,0,0,0);
  height: 1px;
  margin: -1px;
  min-width: 0;
  overflow: hidden;
  padding: 0;
  position: absolute;
  white-space: nowrap;
  width: 1px;
}

Rather than adding more JavaScript or another class, instead, I expanded it like this (I'm using SCSS):

.sr-only, .js [data-js="hidden"] {
  border: 0;
  clip: rect(0,0,0,0);
  height: 1px;
  margin: -1px;
  min-width: 0;
  overflow: hidden;
  padding: 0;
  position: absolute;
  white-space: nowrap;
  width: 1px;

  // Never forget our keyboard navigating siblings.
  &:focus {
    height: auto;
    margin: unset;
    min-width: unset;
    overflow: visible;
    padding: unset;
    position: static;
    width: auto;
  }
}

Note that one limitation with my use of the data-js attribute is that it's not particularly expandable - trying to add a second value to the attribute will break the pattern, unless I started using a pattern along the lines of [data-js^="hidden"], [data-js*=" hidden"]. I'll revisit this if it becomes an issue.

Anyway, it worked a treat and my hidden submit button pops out when required. Mouse-driven users and touch users probably won't ever see it. Dunno if this might be useful to someone. Feel free to reuse it.

Update

Well, that didn't take long. What I'd forgotten was that I'm heavily abusing checkboxes and radio buttons for various tasks around the site, all of which popped up when I added this code (and they went into focus, of course). For the moment, I've locked this behaviour behind an .kb-focus:focus selector, which makes it opt-in.

Posted on by:

rossangus profile

Ross Angus

@rossangus

My interests are quirks of CSS, accessibility and "doing interesting things with old technology", apparently.

Discussion

markdown guide