Focus Shift Demo

This page demonstrates situations where page focus should be shifted to aid usability and shows how to do it in a ways that avoids confusion.

Expandable Search

In this situation, there is stuff and links between the expand button and the thing being expanded. This makes the expanded information hard to find. The focus will jump over this when the search is expanded. Since the focus is shifting in an unexpected way, an aria-label is added to the button to alert users to the behavior before they click.

Note - This does not trap the focus within the expanded section. The user can leave the search open without interfereing with the rest of the content, so there is no reason to contain them within that scope.

Here is the HTML:

<p><button class="search-toggle-btn btn btn-primary" type="button" data-toggle="collapse" data-target="#searchWrap" aria-expanded="false" aria-controls="searchWrap" aria-label="Site Search. Clicking will jump to the search field.">
  Site Search
</button></p>
<p>...</p>
<div class="collapse" id="searchWrap">
  <div class="well">
    <form>
      <div class="form-group">
        <label class="control-label" for="searchInput">Site search</label>
        <input type="text" class="form-control" id="searchInput" placeholder="Keywords">
      </div>
      <div class="form-group">
        <input class="btn btn-primary" type="submit" value="Submit Search">
      </div>
    </form>
    <button id="closeSearch" class="close" type="button" aria-label="Close search." data-toggle="collapse" data-target="#searchWrap" aria-controls="searchWrap">
      <span aria-hidden="true">×</span>
    </button>
  </div>
</div>

Here is the javascript

    // focus search field on expand
$('#searchWrap').on('shown.bs.collapse', function() {
  document.getElementById('searchInput').focus();
  console.log('Shifting focus to input field.');
});

// shift focus back to the search toggle button
$('#closeSearch').on('click', function(event) {
  document.querySelector('.search-toggle-btn').focus();
  console.log('Put focus back on button.');
});