Halloween Sale 15% off Ends in See the plans
HTML

Make Scrollable Areas Reachable by Keyboard

Finds code blocks, tables and other boxes that scroll sideways or vertically but contain nothing focusable, and makes them keyboard-focusable with a label, so keyboard users can scroll them with the arrow keys.

Don’t have WPIDE yet? Install it on your site

Code

<script>
(function () {
    function fix() {
        document.querySelectorAll('pre, .wp-block-table, .wp-block-code, figure, .table-responsive, [style*="overflow"]').forEach(function (el) {
            var scrolls = el.scrollWidth > el.clientWidth + 2 || el.scrollHeight > el.clientHeight + 2;
            var style = getComputedStyle(el);
            var canScroll = /(auto|scroll)/.test(style.overflowX + style.overflowY);
            if (!scrolls || !canScroll || el.hasAttribute('tabindex') || el.querySelector('a[href], button, input, select, textarea, [tabindex]')) { return; }
            el.setAttribute('tabindex', '0');
            if (!el.getAttribute('role')) { el.setAttribute('role', 'region'); }
            if (!el.getAttribute('aria-label')) {
                var caption = el.querySelector('caption, figcaption');
                el.setAttribute('aria-label', caption ? caption.textContent.trim() : (el.tagName === 'PRE' || el.querySelector('code') ? 'Code example' : 'Scrollable content'));
            }
        });
    }
    window.addEventListener('load', fix);
    var timer;
    window.addEventListener('resize', function () { clearTimeout(timer); timer = setTimeout(fix, 300); });
})();
</script>

Notes

Runs once after the page loads and again when the window is resized.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.