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)">
☰
</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.