DEV Community 👩‍💻👨‍💻

Himanshupal0001
Himanshupal0001

Posted on

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)

Top Heroku Alternatives (For Free)

>> Check out this classic DEV post <<