1

I need a <div> that should be able to get key down events. For that reason I have to add the attribute tabindex="0", as suggested here.

The "collateral effect" is that the <div> become "tabbable" and this is not desired because tab should just traverse input fields.

Is there a "trick" to avoid it or the only way is to catch the tab event, search for the next input field (so skipping DIVs) and than prevent the default behavior?

Neo
  • 1,337
  • 4
  • 21
  • 50
  • Why you want div to have key down events and don't want to have focus on that element. You want to get keydown events when click it? – jcubic Sep 04 '19 at 11:40
  • Yes I want keydown events but I don't want the element to be traversable with tab – Neo Sep 04 '19 at 12:24
  • what about setting tabindex="-1"? Seems to work in FF an Chrome – Neo Sep 10 '19 at 12:03

2 Answers2

1

You can test with this.

function doSomething(ctrl)
{
    // Prevent default behaviour
    event.preventDefault();
    
    if (event.key === 'Enter')
    {
        ctrl.innerHTML = 'Enter is pressed';
    }
    else if (event.key === 'ArrowDown')
    {
        ctrl.innerHTML = 'ArrowDown is pressed';
    }
}
<div onkeydown="doSomething(this);" contenteditable="true" readonly style="outline:none;">flsdkjflsajdflkasjdlfkjsaldfkjlksadfj</div>
0

What about setting tabindex="-1"? Seems to work in FF an Chrome

Neo
  • 1,337
  • 4
  • 21
  • 50