DEV Community

Himanshupal0001
Himanshupal0001

Posted on

1

Why TabIndex = '0' in Divs for keyboard events (onKeydown) in js ?πŸ‘¨β€πŸŽ“

First thing first What and Why TabIndex?

TabIndex is a property in js to let the computer know that keyboard button has been pressed. In HTML, mostly forms are focus types but not divs. In order to detect any key has been pressed or not JavaScript expect the element must in focus to detect any input.

TabIndex is a global attribute that tell the browser that this element can be focused.

For example if you want to know the keycode and key on onkeydown event you can check the below code.



function App() {

  const [toggle, setToggle] = useState(false);
  const [history, setHistory] = useState([]);
  const [exp, setExp] = useState('');
  const [result, setResult] = useState('');


  const handleKeypress = (keyCode, key) => {
    console.log(keyCode, key);

  }

  return (
    <div className='app' data-theme={toggle ? 'dark' : ''}
      tabIndex='0'
      onKeyDown={e => handleKeypress(e.keyCode, e.key)}>
      <div className='body'>
        <div className='navbar'>
          <div className='navbar-toggle-body'>
            <div className='navbar-toggle' onClick={() => setToggle(!toggle)}>
              <div className={`navbar-toggle-circle ${toggle ? 'navbar-toggle-circle-active' : ''}`} />
            </div>
            {toggle ?
              <p>πŸŒ™</p> : <p>🌞</p>
            }
          </div>
        </div>
        <Header />
        <Keypad />
      </div>
    </div>
  );
}

export default App;



Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay