0

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);
}

2 Answers2

0
 <button id="btn3" aria-expanded="false" onclick="myFunction3(this)"> Menu </button>
function myFunction3(el) {
   bx = el.getAttribute("aria-expanded"), 
   newBx = (bx == "true") ? false : true;   
   el.classList.toggle("close");
   el.setAttribute("aria-expanded", newBx);
}
0

I think better to use modern DOM API:

<nav aria-label="resp menu">
    <button id="btn3" aria-expanded="false"> 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
 let element = document.getElementById('btn3');
 element.addEventListener('click', function(e) {
   this.classList.toggle("close");
   let bx = this.getAttribute("aria-expanded") == "true" ? false : true;
   this.setAttribute("aria-expanded", bx );
 });
Salvio
  • 100
  • 2
  • 15