aboutsummaryrefslogtreecommitdiffstats
path: root/demo/src/js/tab-focus.js
blob: c1602cf01cb031d58cb4173710dad23ba9ca9f74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Setup tab focus
const container = document.getElementById('container');
const tabClassName = 'tab-focus';

// Remove class on blur
document.addEventListener('focusout', event => {
    if (!event.target.classList || container.contains(event.target)) {
        return;
    }

    event.target.classList.remove(tabClassName);
});

// Add classname to tabbed elements
document.addEventListener('keydown', event => {
    if (event.keyCode !== 9) {
        return;
    }

    // Delay the adding of classname until the focus has changed
    // This event fires before the focusin event
    setTimeout(() => {
        const focused = document.activeElement;

        if (!focused || !focused.classList || container.contains(focused)) {
            return;
        }

        focused.classList.add(tabClassName);
    }, 10);
});