I want my Bootstrap tab switchers to stop eating Up and Down keys, so the page could scroll instead, as if they are not focused.
$('input[type="radio"][role="tab"]').on('keydown keyup', function (e)
{
if (e.key == 'ArrowDown' || e.key == 'ArrowUp')
{
e.stopImmediatePropagation();
e.preventDefault();
// So far so good.
$('body')[0].dispatchEvent(new KeyboardEvent(e.type, { 'key': e.key }));
// No effect :(
}
});
The code above made the controls stop responding to Up and Down, but unfortunately the page doesn’t scroll nevertheless.
UPD Here’s MRE: https://getbootstrap.com/docs/5.3/forms/checks-radios/#radio-toggle-buttons. Click any of the buttons (“Checked” or “Radio”) and try pressing ←, ↑, ↓ and →. I’m fine with ← and →, but I want the page to scroll, when I press ↓ and ↑.
UPD2 This kind of works:
$('input[type="radio"][role="tab"]').on('keydown keyup', function (e)
{
if (e.key == 'ArrowDown' || e.key == 'ArrowUp')
{
e.stopImmediatePropagation();
e.preventDefault();
document.activeElement.blur();
}
});
After the first pressing on ↓ or ↑, the element loses focus, then the page starts scrolling as usual. Not exactly what I wanted, but it’s even better from UX viewpoint, I guess.
2
Answers
You need to NOT prevent default so scrolling works. I could have tested this if you had posted an example with HTML
Try this
I don’t think re-dispatching the keyboard event will work. It might work for entering text into a field but probably not for scrolling a document.
I suggest you stick with preventDefault, and take control of the scroll yourself. You might need to change that part of the code to suit your page, but here’s my example.