I want to use a javascript function for the onclick event. (On the button). Toggles css class + aria-expanded attribute. It works. I was inspired by w3school. There are understandable codes.
If I have 20 submenus on my website, do I have to write this code 20 times? For each specific ID?
HTML
<nav aria-label="resp menu">
<button id="btn3" aria-expanded="false" onclick="myFunction3()"> Menu </button>
<ul>
<li><a href="#">Prvá položka</a></li>
<li><a href="#">Prvá položka</a></li>
<li><a href="#">Prvá položka</a></li>
</ul>
</nav>type here
Javascript function
function myFunction3() {
var element = document.getElementById("btn3");
element.classList.toggle("close");
var bx = document.getElementById("btn3").getAttribute("aria-expanded");
if (bx == "true")
{
bx = "false"
} else {
bx = "true"
}
document.getElementById("btn3").setAttribute("aria-expanded", bx);
}
3
Answers
you can achieve this by passing the this operator to the function it self like so
for HTML
for JS
I think better to use modern DOM API: