Why TabIndex = '0' in Divs for keyboard events (onKeydown) in js ?👨‍🎓
Himanshupal0001

Himanshupal0001 @himanshupal0001

About: Full stack web Dev. Like to teach and learn. Open for free lance and open source projects.

Location:
DXB
Joined:
Nov 21, 2021

Why TabIndex = '0' in Divs for keyboard events (onKeydown) in js ?👨‍🎓

Publish Date: Nov 11 '22
1 0

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

Comments 0 total

    Add comment