Techniques for WCAG 2.0

On this page:

-

# SCR31: Using script to change the background color or border of the element with focus

## Applicability

HTML and XHTML, CSS, Script

This technique relates to:

- Success Criterion 2.4.7 (Focus Visible)
  - How to Meet 2.4.7 (Focus Visible)
  - Understanding Success Criterion 2.4.7 (Focus Visible)

## User Agent and Assistive Technology Support Notes

This technique can be used on user agents that don't support the `:focus` pseudoclass but do support script, including Microsoft Internet Explorer.

## Description

This purpose of this technique is to allow the author to use JavaScript to apply CSS, in order to make the focus indicator more visible than it would ordinarily be. When an element receives focus, the background color or border is changed to make it visually distinct. When the element loses focus, it returns to its normal styling. This technique can be used on any HTML user agent that supports Script and CSS, regardless of whether it supports the :focus pseudoclass.

## Examples

### Example 1

In this example, when the link receives focus, its background turns yellow. When it loses focus, the yellow is removed. Note that if the link had a background color to begin with, you would use that color rather than "" in the script.

Example Code:

    ...
    <script>
     function toggleFocus(el)
     {
      el.style.backgroundColor =  el.style.backgroundColor=="yellow" ? "inherit" : "yellow";
     }
    </script>

    ...

    <a href="example.html" onfocus="toggleFocus(this)" onblur="toggleFocus(this)">focus me</a>
    ...

## Related Techniques

- C15: Using CSS to change the presentation of a user interface component when it receives focus

## Tests

### Procedure

1. Tab to each element in the page

2. Check that the focus indicator is visible

### Expected Results

- Step #2 is true

- Top
- Contents
- Intro
- Previous: Technique SCR30
- Next: Technique SCR32