skip to Main Content

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


  1. you can achieve this by passing the this operator to the function it self like so

    for HTML

    <nav aria-label="resp menu">
    <button id="btn3" aria-expanded="false" onclick="toggleMenu(this)">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>
    

    for JS

    function toggleMenu(button) {
        button.classList.toggle("close");
        const isExpanded = button.getAttribute("aria-expanded") === "true";
        button.setAttribute("aria-expanded", !isExpanded);
    }
    
    Login or Signup to reply.
  2.  <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);
    }
    
    Login or Signup to reply.
  3. 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 );
     });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search