bilc
bilc

Reputation: 47

Javascript hide/show on click not working

I'm trying to make a drop-down list using Html and Javascript, but it is not working for some reason, despite watching every video on Youtube. Here's the code I'm using: HTML:

<div class="dropdown">
    <button id="dropdownbtn" onclick="dropdown()">Courses &#9662</button>
    <div id="dropdown-items">
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
    </div>
</div>

JavaScript:

var flag = 0;
function dropdown() {

    if (flag==0) {
        document.getElementById("dropdown-items").style.display = "none";
        flag=1;
    } 

    if (flag==1) {
        document.getElementById("dropdown-items").style.display = "block";
        flag=0;
    }
}

I set the display to none in css also. Thank you for your help.

Upvotes: 0

Views: 93

Answers (3)

Sanjun Dev
Sanjun Dev

Reputation: 518

Why not use toggleclass here?

    <div class="dropdown">
    <button id="dropdownbtn" onclick="dropdown()">Courses &#9662</button>
    <div id="dropdown-items">
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
        <li class="li"><a href="#" class="li">button!!</a></li>
    </div>
    </div>

add css like

#dropdown-items {
 display: none;
}

.toggleShow {
  display: block;
}

In your script

<script>
function dropdown() {
   var element = document.getElementById("dropdown-items");
   element.classList.toggle("toggleShow");
}
</script>

Upvotes: 1

EugenSunic
EugenSunic

Reputation: 13693

An easier solution, use ternary operators:

document.getElementById("dropdown-items").style.display = flag === 0 ? 'none' : ' block'

Upvotes: 1

Amy
Amy

Reputation: 35

it's actually working but you have to place else if because in if condition you change the flag with 1 and also second condition becomes true

var flag = 0;

function dropdown() {

    if (flag==0) {

        document.getElementById("dropdown-items").style.display = "none";

        flag=1;
    } 
    else if (flag==1) {

        document.getElementById("dropdown-items").style.display = "block";

        flag=0;
    }
}

Upvotes: 1

Related Questions