Natalia Bizitza
Natalia Bizitza

Reputation: 113

Dropdown menu elements lose focus on tab

My dropdown menu button opens on hover (CSS), but its content is not accessible on the tab.

On button- tab, the dropdown menu opens on next tab press it skips all content of the menu, closes it and continues to go to the next focus elements on the page.

I need to be able to tab through the menu. This from my react component:

<div className="dropdown" 
        tabIndex="0"
        role="navigation">
          <button className="dropBtn" tabIndex="0" role="menu" type="button" aria-expanded="false" aria-controls="navbar">
            <i className="hover">Places</i>
          </button>
          <div tabIndex="0" className="dropdown-content">
          <div tabIndex='0' className='filter'>
            <input 
              className='input'
              tabIndex="0"
              type="text"
              placeholder="Search your place"
              value={this.props.query}            
              onChange={e => this.props.handleUpdateQuery(e.target.value)}/>
              </div>
             {/* <div className="search-places-results"> */}
             <ul className='listOfPlaces' 
             role="menubar">
              {this.props.filteredPlaces.map((item)=>{
                return <li item={item} 
                tabIndex="0"
                role="menuitem"
                items={this.props.places} 
                key={item.id}
                onClick={(e)=>{this.props.onItemClick(e, item.id)}}>
                {item.name}</li>
              })}
             </ul>
            {/* </div> */}
          </div>
        </div> 

CSS:

.dropdown-content .filter:hover,
.dropdown-content .filter:focus,
.dropdown-content ul li:hover,
.dropdown-content ul li:focus {
  background-color: rgb(41, 160, 240);
}

.dropdown:hover .dropdown-content,
 .dropdown:focus .dropdown-content {
  display: block;
}

This is how it opens on tab press

Upvotes: 3

Views: 5251

Answers (2)

jmargolisvt
jmargolisvt

Reputation: 6088

Without running this, I see a couple possibilities here. First of all, I wouldn't expect tabbing to work because you've given them all the same tabindex. See your map function which assigns a hard value of zero to all of you list elements. map has a second param you can pass which is an index. Use that to generate tabindexes instead.

[1, 2, 3].map((x, i) => console.log(i))

Second, you are not attaching your tabindexes to anchors. This creates an a11y problem. Try adding menuitem or maybe link aria roles to your list items. As suggested by MDN, using native anchor elements is probably your best bet. https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_link_role

Upvotes: 2

Natalia Bizitza
Natalia Bizitza

Reputation: 113

To fix it I used focus:within :

.dropdown:focus-within .dropdown-content {
  display: block
}

Upvotes: 1

Related Questions