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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.