One of the more frustrating things about accessibility is how ridiculously easy most things are to do. While most developers tend to see accessibility as nebulous and time consuming, the truth is some of the most impactful issues are actually easy to deal with. As a case-in-point: consider simple keyboard accessibility for custom controls otherwise activated by click. For the <button> element, you get free accessibility. It appears in the tab order and reacts appropriately to both click and keypress via the enter and spacebar. This is not the case for custom controls, such as those created with DIV and span. Typically you’ll see developers do something like this:

$('#fake-button').on('click', function() {
    //do stuff
});

The problem with the code above is that it only works when the user clicks the mouse button. So for whatever this button does on click, it absolutely does nothing when the enter key (or space bar) is pressed, which is how one expects to interact with buttons via keyboard. The solution is, obviously, to check for keypress too. BUT don’t do this:

$('#fake-button').on('click keypress', function() {
    //do stuff
});

That will trigger on any keypress, including the TAB key. For a keyboard user that would be a bit like triggering on mouseover. Instead, you need a function to check the specific key(s):

function a11yClick(event){
    if(event.type === 'click'){
        return true;
    }
    else if(event.type === 'keypress'){
        var code = event.charCode || event.keyCode;
        if((code === 32)|| (code === 13)){
            return true;
        }
    }
    else{
        return false;
    }
}

That function returns TRUE on either click or whenever the space bar or enter key have been pressed. Now all you need to do is this:

$('#fake-button').on('click keypress', function(event){
  if(a11yClick(event) === true){
    // do stuff
  }
});

Given how simple this is, developers really have no excuse for using only ‘click’ on controls.

My company, AFixt exists to do one thing: Fix accessibility issues in websites, apps, and software. If you need help, get in touch with me now!