0

I am trying to supplement the well-known checkbox hack for menu in CSS with JavaScript, since JavaScript is the only way (I know) to update HTML attributes, in which case I need here for the ARIA attributes.

I implemented the default behaviour with CSS which works well (but of course doesn't update the ARIA attributes), so I want to ad JavaScript to do that. However an error of null is thrown when I try to access the checked attribute of the checkbox element. Below is a snippet of the code below (other elements are removed to keep it simple). Thank you.

<input id="header__checkbox" type="checkbox" hidden>
<header>
  <nav>
    <label class="menu-button" for="header__checkbox" tabindex="0" role="button"
      aria-pressed="false" aria-label="menu" aria-haspopup="menu" onclick="toggleMenu(event)"
      onkeydown="toggleMenu(event)">
      &#9776;
    </label>

    <ul class="menu" aria-hidden="true"></ul>
  </nav>
</header>
const hiddenCheckbox = document.getElementById("header__checkbox");
const menuButton = document.querySelector(".menu-button");
const menu = document.querySelector(".menu");

function toggleMenu(event) {
  if (event.type === "click" ||
     (event instanceof KeyboardEvent && (event.key === "Enter" || event.key === " "))) {
    event.preventDefault();
    hiddenCheckbox.checked = !hiddenCheckbox.checked;
    menuButton.setAttribute("aria-pressed", hiddenCheckbox.checked);
    menu.setAttribute("aria-hidden", !hiddenCheckbox.checked);
  }
}

From DevTools, this !hiddenCheckbox.checked; throws an error, which I am confused as to why.

  • 1
    For those of us who don't know, what is the "well known checkbox hack"? – Barmar Aug 10 '23 at 21:40
  • Please post the exact error message. – Barmar Aug 10 '23 at 21:40
  • 1
    If your script is in the head of the document (or anywhere above the checkbox) and not waiting for a load event before running) it is running before the checkbox is there. In that case `hiddenCheckbox` is `null`, and trying to access `hiddenCheckbox.checked` will throw the error you're seeing. Try moving the script to the end of the document, just inside the closing body tag. – ray Aug 10 '23 at 21:40
  • Well I guess using "defer" on the script or moving it down as you suggested worked. Thank you so much. But then it's surprising to see that only clicking on the menu again will remove it from the screen. I thought JS would do that automatically. How would one go about that? – Udoh Jeremiah Aug 10 '23 at 21:54

0 Answers0