Do Not Cause Context Change When an Element Receives Focus
Why It Matters
Unexpected changes of context triggered merely by moving focus (e.g., tabbing to a field) can be extremely disorienting for users, especially those with cognitive or visual impairments. Users expect to be able to navigate through interactive elements without triggering actions until they explicitly choose to do so (e.g., by clicking, pressing Enter/Space).
Fixing the Issue
Ensure that setting focus to an element does not, by itself, cause a major change. Actions like submitting forms, opening new windows, or navigating to new pages should only occur when the user actively activates a control (e.g., clicks a button, presses Enter on a link). Use onfocus event handlers only for changes that don’t significantly alter the context, such as displaying help text related to the focused field or highlighting the element.
Good Code Example
Using onfocus for a non-disruptive action (showing help text):
-
<label for="password">Password:</label> <input type="password" id="password" name="pwd" aria-describedby="pwd-help"> <span id="pwd-help" style="display: none; color: #555;"> Password must be at least 8 characters long. </span> <script> const passwordInput = document.getElementById('password'); const helpText = document.getElementById('pwd-help'); passwordInput.addEventListener('focus', () => { // Showing related help text is acceptable on focus helpText.style.display = 'block'; }); passwordInput.addEventListener('blur', () => { // Hide help text when focus leaves helpText.style.display = 'none'; }); </script>
-
Password must be at least 8 characters long.
Bad Code Example
Triggering navigation just by focusing on a radio button:
-
<fieldset> <legend>Select Destination:</legend> <input type="radio" id="dest1" name="destination" value="page1" onfocus="window.open('https://www.accessitree.com/', '_blank')"> <label for="dest1">Page 1</label> <input type="radio" id="dest2" name="destination" value="page2" onfocus="window.open('https://www.accessitree.com/contact/', '_blank')"> <label for="dest2">Page 2</label> </fieldset>
