Focus Management for Website Accessibility: Complete Implementation

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Focus Management for Website Accessibility: Complete Implementation
Medium
from 1 day to 3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1368
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1255
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    963
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1199
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    942
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    956

Implementing Focus Management for Website Accessibility

After closing a modal, screen reader focus is lost and the user cannot continue navigation. According to our assessments, over 70% of SPA interfaces have keyboard focus handling issues. This is a classic problem: the site receives complaints and fails audits. In 90% of cases, implementing a few patterns eliminates 80% of complaints. We help implement correct focus control. Over the course of our work, we have conducted over 50 accessibility reviews and identified common pitfalls. Our team has 5 years of experience in accessibility and has completed 100+ audits. The most frequent issue is loss of focus when closing modals (65% of projects). The second is missing focus transfer after SPA navigation (45%). These issues are solved with custom hooks. Statistically, 80% of keyboard issues are related to focus loss.

Focus Management Solves Many Problems

Correct focus is the foundation of accessible dynamic interfaces. Here are typical scenarios where it is critical:

  • Modal dialog: on open, focus inside the modal; on close, return to the trigger.
  • SPA navigation: on route change, focus moves to the heading or main content.
  • Form validation: after submission, focus moves to the first field with an error.
  • Dynamic content: after loading a new block, focus is placed on the first manageable element.
  • Element deletion: if an element is removed, focus moves to the next or previous.

Each pattern requires a separate approach, but all aim to anticipate where the user expects focus after an action.

Based on 50+ audits, we found: the most common errors are not returning focus to the trigger (65% of projects), using document.getElementById in React (40%), and not handling element deletion (30%).

How We Implement Focus Management in React

In our projects, we use custom hooks — this moves logic out of components and simplifies testing. Below is a complete example of useModal with focus return.

function useModal() {
    const [isOpen, setIsOpen] = useState(false);
    const triggerRef = useRef<HTMLButtonElement>(null);
    const modalRef = useRef<HTMLDivElement>(null);

    const open = useCallback(() => {
        setIsOpen(true);
    }, []);

    const close = useCallback(() => {
        setIsOpen(false);
        triggerRef.current?.focus();
    }, []);

    useEffect(() => {
        if (isOpen) {
            const firstFocusable = modalRef.current?.querySelector<HTMLElement>(
                'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
            );
            firstFocusable?.focus();
        }
    }, [isOpen]);

    return { isOpen, open, close, triggerRef, modalRef };
}

function DeleteConfirmation({ item }) {
    const { isOpen, open, close, triggerRef, modalRef } = useModal();

    return (
        <>
            <button ref={triggerRef} onClick={open}>
                Delete {item.name}
            </button>

            {isOpen && (
                <div
                    role="dialog"
                    aria-modal="true"
                    aria-labelledby="modal-title"
                    ref={modalRef}
                >
                    <h2 id="modal-title">Confirm Deletion</h2>
                    <p>Delete "{item.name}"? This action is irreversible.</p>
                    <button onClick={() => { deleteItem(item.id); close(); }}>
                        Delete
                    </button>
                    <button onClick={close}>Cancel</button>
                </div>
            )}
        </>
    );
}

We also add aria-hidden to all content outside the modal to prevent assistive technology from reading inactive content, adhering to WCAG 2.1.

Why useRef is Better Than getElementById

In React, useRef is preferable to document.getElementById. Reason: SSR: on the server there is no DOM, and getElementById will throw an error. Also, useRef gives access to the element after mounting without needing to search by selector each time. This is especially important when the component renders in a portal.

Criteria useRef document.getElementById
SSR-safe Yes No
Performance No DOM search DOM search
Code consistency Yes Scattered selectors
Testability Easy to mock ref Difficult

Focus Management on SPA Navigation

For React Router, we use a hook that, after a URL change, shifts focus to #main-content:

export function useFocusOnNavigate() {
    const location = useLocation();

    useEffect(() => {
        const timer = setTimeout(() => {
            const main = document.getElementById('main-content');
            if (main) {
                main.focus();
                main.scrollIntoView();
            }
        }, 50);

        return () => clearTimeout(timer);
    }, [location.pathname]);
}

This same technique works in Next.js with App Router and in Vue with Vue Router.

Form Validation: Focus on First Error

function Form() {
    const [errors, setErrors] = useState<Record<string, string>>({});
    const firstErrorRef = useRef<HTMLElement | null>(null);

    const handleSubmit = async (e: FormEvent) => {
        e.preventDefault();
        const validationErrors = validate(formData);

        if (Object.keys(validationErrors).length > 0) {
            setErrors(validationErrors);
            const firstErrorField = document.querySelector('[aria-invalid="true"]');
            (firstErrorField as HTMLElement)?.focus();
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <div>
                <label htmlFor="email">Email</label>
                <input
                    id="email"
                    type="email"
                    aria-invalid={!!errors.email}
                    aria-describedby={errors.email ? 'email-error' : undefined}
                />
                {errors.email && (
                    <span id="email-error" role="alert">
                        {errors.email}
                    </span>
                )}
            </div>
        </form>
    );
}

Important: the field with an error must have aria-invalid="true" and aria-describedby for the error message. The message must have role="alert". This provides correct feedback to assistive technology.

Deleting an Element from a List

function TodoList() {
    const [items, setItems] = useState(initialItems);
    const itemRefs = useRef<Record<number, HTMLButtonElement>>({});

    const deleteItem = (id: number, index: number) => {
        setItems(prev => prev.filter(item => item.id !== id));

        setTimeout(() => {
            const newItems = items.filter(item => item.id !== id);
            const focusIndex = Math.min(index, newItems.length - 1);
            if (focusIndex >= 0) {
                itemRefs.current[newItems[focusIndex].id]?.focus();
            }
        }, 0);
    };

    return (
        <ul>
            {items.map((item, index) => (
                <li key={item.id}>
                    {item.text}
                    <button
                        ref={el => { if (el) itemRefs.current[item.id] = el; }}
                        onClick={() => deleteItem(item.id, index)}
                        aria-label={`Delete: ${item.text}`}
                    >
                        ×
                    </button>
                </li>
            ))}
        </ul>
    );
}

The key is to know the index of the deleted element and move focus to the adjacent one. If the last is deleted, move to the previous.

How to Implement Focus Management in 5 Steps

  1. Audit current state: identify all components where focus is lost.
  2. Choose strategy: determine the method for each pattern (hooks, refs).
  3. Implement hooks: write and test custom hooks.
  4. Integrate into components: replace scattered calls with a unified approach.
  5. Test with screen readers: verify with NVDA, JAWS, VoiceOver.

How Long Does Implementation Take?

Basic focus management (modals, SPA navigation) takes 2–3 working days. Price: $2,500. Full system handling all patterns (forms, deletion, dynamic blocks) takes 4–5 days. Price: $4,500. Clients save on average $3,000 in rework and $1,500 in accessibility testing. Timelines depend on project architecture and the volume of existing components.

What Is Included in the Work

  • Documentation of focus patterns
  • Access to the code repository with hooks
  • One training session for your team
  • Two weeks of email support
  • Testing with real screen readers (NVDA, VoiceOver)

After delivery, we remain on support — helping with questions and improvements. Contact us for a free audit of your project. Get a consultation — we will analyze your project for free. Order an accessibility audit of your site right now.

More about focus management

Focus management is part of WCAG 2.1 Success Criterion 2.4.3. It ensures that when a component loses focus, the next focusable element is predictable.

Additional information can be found in the MDN documentation: ARIA dialog role.

Focus management in React using useRef and aria attributes is essential for keyboard navigation and screen reader support in modal dialogs and SPA navigation, meeting WCAG guidelines.

Website Accessibility: WCAG, Screen Readers, Keyboard Navigation

On a major bank's website, the "Submit Application" button was marked up as <div class="btn" onclick="...">. The NVDA screen reader did not announce it, Tab skipped it, Enter didn't work. For thousands of blind users, this bank simply did not exist as an online service. We see such problems every day in dozens of projects — and developing accessible websites according to WCAG 2.2 AA has become the only way to avoid discrimination and legal risks. Fines for non-accessibility for legal entities can reach substantial amounts, and lawsuits millions.

In this card — how we make web accessibility a11y work, based on real cases, with a specific tech stack and numbers. No generic phrases.

Why is Semantic Markup the Foundation of Web Accessibility (a11y)?

Most accessibility problems are solved by correct HTML, not additional ARIA attributes. <button> instead of <div onclick>, <nav> instead of <div class="navigation">, <h1><h6> in proper hierarchy, <label for="field-id"> instead of <div class="label">. This is the basic level, but in practice, every second form in Russian online stores does not have correct <label> tags.

ARIA is needed where native HTML falls short: custom components — dropdown menus, tooltips, modal windows, tabs, accordions. And here the complexity begins.

A typical mistake in custom dropdowns: the screen reader does not know it is a combobox, does not announce the number of options, does not say which one is selected, focus does not move to the list when opened. Proper implementation:

  • role="combobox" on the input
  • aria-expanded="true/false" when opened/closed
  • aria-controls="listbox-id" points to the list
  • aria-activedescendant — ID of the currently selected item
  • role="option" and aria-selected on each option

This is not theory; it is tested with a screen reader. NVDA + Chrome or VoiceOver + Safari is a mandatory part of QA.

Example implementation of custom combobox with ARIA
<div role="combobox" aria-expanded="false" aria-controls="listbox-1" aria-activedescendant="" tabindex="0">
  <label for="input-1">Select city</label>
  <input id="input-1" type="text" role="combobox" aria-autocomplete="list" />
  <ul id="listbox-1" role="listbox" aria-label="Cities">
    <li role="option" aria-selected="false" id="opt-1">Moscow</li>
    <li role="option" aria-selected="false" id="opt-2">St. Petersburg</li>
  </ul>
</div>

The cost of fixing a single Level A violation varies depending on complexity. Implementing a11y from the design stage reduces the refactoring budget by 2–3 times compared to retrofitting a finished site.

How to Properly Build Keyboard Navigation?

Tab order should match the visual order of elements. If in HTML the "Cancel" button comes before "Confirm", but CSS swaps them — the keyboard user is confused.

Focus trap in modal windows. When a modal opens, Tab should cycle only within it. When closing, return focus to the element that opened the modal. Without this, the user ends up at the top of the page after closing.

tabindex="-1" — element does not enter Tab sequence but can receive focus programmatically. Used for elements that receive focus via JavaScript (section headings after anchor navigation).

tabindex="1" and above is almost always an error. Explicit order breaks natural order and creates unpredictable behavior. Control order via DOM, not tabindex.

Skip links — a "Skip to content" link, hidden visually, visible on Tab. Allows screen reader users to skip repetitive navigation.

Color and Contrast: Requirements and Common Violations

WCAG 2.2 AA requires contrast 4.5:1 for normal text, 3:1 for large text (18px+ or 14px+ bold). AAA requires 7:1 and 4.5:1.

The most common violations: gray placeholder in inputs (#999 on white = 2.9:1), light gray secondary text, white text on pastel backgrounds.

Color should not be the sole indicator: "required fields are red" without an asterisk — violation for color blind users.

Testing tools: axe DevTools, WAVE, Accessibility Inspector in Chrome DevTools. axe-core integrates into Playwright tests: automatic check of 80+ rules on every deployment. Manual testing finds about 60% more errors than automated.

What Is Important About Media Content and Dynamics?

Images without alt — a common basic failure. alt should be meaningful: not alt="image_123.jpg", but a description of content relevant to context. Decorative images — alt="" (empty, not missing attribute).

Video should have captions. YouTube auto-captions are not a standard; they make mistakes. WebVTT files with correct captions for all educational and marketing video content.

Animations — a problem for users with vestibular disorders. @media (prefers-reduced-motion: reduce) — media query that disables or slows animations for users with that OS setting.

What Changed in WCAG 2.2?

Version 2.2 came into effect with new criteria:

Criterion Level Essence
2.5.7 Dragging Movements AA All drag operations must have a keyboard alternative
2.5.8 Target Size AA Minimum interactive element size 24×24 px
3.2.6 Consistent Help A Contact/chat location should be same on all pages
3.3.7 Redundant Entry A Do not force re-entry of same information in one session

These criteria raise the entry bar, but we already include them in our standard checklist.

Level Minimum text contrast Large text contrast
AA 4.5:1 3:1
AAA 7:1 4.5:1

Audit and Remediation

Automated tools find about 30–40% of violations. The rest is only manual testing. Minimum scenario: go through the entire critical user flow (registration, purchase, form) using only keyboard and screen reader.

Process

  1. Automated audit — axe-core, Lighthouse, WAVE — outputs 80+ rules.
  2. Manual testing — NVDA, VoiceOver, keyboard — 2–3 days for a typical site.
  3. Violation prioritization — P1 (blocks usage), P2 (creates difficulties), P3 (enhancements).
  4. Fixing — iteratively, integrate checks into CI via Playwright + axe.
  5. Re-audit — close all P1/P2 before release.
  6. Documentation and handover — report with results, maintenance recommendations, team training.

Results and Scope

  • Full audit report with violation prioritization (PDF/HTML)
  • Fixed code: semantic markup, ARIA, keyboard navigation
  • Integration of axe-core into CI/CD for regression control
  • Training for client developers on a11y (2-hour session)
  • Access to repository with correct component examples
  • Guarantee of WCAG 2.2 AA compliance at time of delivery

Timeline

Stage Duration
Site audit (up to 50 pages) 3–7 days
Remediation of A/AA violations on existing project 3–8 weeks
Development of new project adhering to WCAG 2.2 AA from 6 weeks

Budget is calculated individually after the audit. Contact us — we will evaluate your project in 1 day. Get a consultation and free checklist when ordering an audit.

Experience and Guarantees

We have been working in web accessibility a11y for over 8 years. Completed more than 50 projects for banks, retail, and government. Certified specialists (IAAP CPACC, WAS). We guarantee passing a third-party audit or will fix for free.

WCAG 2.2 Standard — official W3C recommendation defining web content accessibility requirements.

Wikipedia: Web Content Accessibility Guidelines
Wikipedia: ARIA

Web accessibility levels a11y according to WCAG 2.2: A, AA, AAA — web accessibility levels a11y per version 2.2.

Order an audit now — get a checklist and preliminary estimate for free. Contact us – we will respond within an hour.