aboutsummaryrefslogtreecommitdiff
path: root/resources/assets/javascripts/lib/skip_links.js
blob: 75dc8bbafc5186f62b7f8a15e0fd461d81fc7555 (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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Taken from https://stackoverflow.com/a/42149818
const isSelectorValid = (dummyElement =>
    selector => {
        try {
            dummyElement.querySelector(selector);
        } catch {
            return false;
        }
        return true;
})(document.createDocumentFragment());

const SkipLinks = {
    /**
     * Inserts the list with skip links
     */
    insertSkipLinks: function() {
        jQuery('#skip_link_navigation').prepend(jQuery('#skiplink_list'));
        jQuery('#skip_link_navigation').attr('aria-busy', 'false');
    },

    /**
     * sets the area (of the id) as the current area for tab-navigation
     * and highlights it
     */
    setActiveTarget (id) {
        let fragment = null;
        // set active area only if skip links are activated
        if (!document.getElementById('skip_link_navigation')) {
            return false;
        }
        if (id) {
            fragment = id;
        } else {
            fragment = document.location.hash;
        }

        if (fragment.length > 0 && isSelectorValid(fragment) && document.querySelector(fragment)) {
            if (jQuery(fragment).is(':focusable')) {
                jQuery(fragment)
                    .click()
                    .focus();
            } else {
                //Set the focus on the first focusable element:
                jQuery(fragment).find(':focusable').eq(0).focus();
            }
            return true;
        }
        return false;
    },

    initialize: function() {
        SkipLinks.insertSkipLinks();
    }
};

export default SkipLinks;