Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle on / off? (Javascript)

I'm trying out JS without jQuery. But so far it's much harder.

I'm trying to make a toggle on & off function.

This is the function:

function toggleDropdown(){

   var dropdown = document.getElementById('games-dropdown')

   if (dropdown.display = "none"){
    dropdown.style.display = 'block';
   } else {
    dropdown.display = "none";
   }
}

I call the function here:

<li class="dropdown"><a onclick="toggleDropdown()">GAMES</a></li>
like image 237
Dario Sanchez Martinez Avatar asked Dec 28 '25 22:12

Dario Sanchez Martinez


1 Answers

You're not being consistent about using the style object, you're checking and sometimes setting display directly on dropdown.

You're also using = instead of == for comparison. = is for assignment, not comparison.

So the minimal change is:

function toggleDropdown(){

   var dropdown = document.getElementById('games-dropdown')

   // ----------vvvvv    
   if (dropdown.style.display == "none"){
   // ------------------------^^
     dropdown.style.display = 'block';
   } else {
     dropdown.style.display = "none";
   // --------^^^^^^
   }
}

However, I wouldn't use style at all. I'd use a class that hides the element, which you add and remove:

.hidden {
    display: none;
}

and

function toggleDropdown(){
   document.getElementById('games-dropdown').classList.toggle("hidden");
}

Example:

function toggleDropdown(){
   document.getElementById('games-dropdown').classList.toggle("hidden");
}
.hidden {
      display: none;
  }
<li class="dropdown"><a onclick="toggleDropdown()">GAMES</a></li>
<div id="games-dropdown">
games-dropdown
</div>

You can also make your function more generic by accepting a selector for the element to show/hide:

function toggleDropdown(selector) {
   document.querySelector(selector).classList.toggle("hidden");
}
.hidden {
      display: none;
  }
<ul>
  <li class="dropdown"><a onclick="toggleDropdown('#games-dropdown')">GAMES</a></li>
  <li class="dropdown"><a onclick="toggleDropdown('#games-dropdown2')">GAMES2</a></li>
</ul>
<div id="games-dropdown">
games-dropdown
</div>
<div id="games-dropdown2">
games-dropdown 2
</div>

I used querySelector rather than getElementById so you could use other forms of identifying the element, but of course use getElementById if ou prefer.

like image 192
T.J. Crowder Avatar answered Dec 30 '25 11:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!