Skip to content
Advertisement

How can I focus the onclick onto this icon? (HTML, CSS, JS)

I need help with figuring out how to focus the ‘clicking’ part of this dropdown navbar icon so that I don’t have to click a little to the left of the icon (also the other navbar items) since I’m trying to recreate Mac OS’s navbar.

JavaScript
JavaScript
JavaScript

IMG:
the dropdown only opens when you click a couple of pixels to the left of the icon

Advertisement

Answer

Problem

I found the source where OP came from and I am not surprised why you ran into trouble. W3Schools is a good resource because it’s simple and never over explains things but at times it omits or just overlooks certain details. In the W3School example “Dropdown Menu Inside a Navigation Bar” the following segment of a CSS ruleset is wrong:

JavaScript

focus event only applies to the these tags:

  • <input>
  • <textarea>
  • <select>
  • <a>

It may vary between browsers but the above list is standard. So <button> is usually not focusable.

Solution

  • Change the <button> into an <a>
  • Add e.preventDefault(); to the event handler so the page won’t jump when the <a> is clicked.

The rest of the changes are recommended, but not necessary. Although I strongly suggest that you don’t use inline event handlers:

JavaScript

Instead use:

JavaScript

OR

JavaScript

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement