js newbie js newbie - 2 months ago 12
Javascript Question

drop down submenu in javascript

hope my question is clear

On pressing on the unique button i have on this page, i want to display the menu having three elements only.

the "Languages" item menu wraps a submenu that i want to display only if the user clicks on "Languages"

however for the moment whenever i click on the button, not only the menu appears but also the submenu; and that is not what i want to have.

can you please inform me what is wrong with my code please?

enter image description here

Code:

<!DOCTYPE html>
<html>
<head>
<style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
overflow: auto;
border : 1px solid black;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdownb {
position: relative;
display: inline-block;
}
.show {display:block;}
</style>
</head>

<body>
<div class="dropdown">
<button id="btn" onclick = "myFunction2()" >Show</button>
<div id="myDropdown" class="dropdown-content">
<p >Countries</p>
<p id="btnl" onclick = "myFunction3()">Languages</p>
<div id = "languageslist">
<a href="">English</a>
<a href="">Spanish</a>
<a href="">German</a>
</div>
<p>Continents</p>
</div>
</div>

<script>
function myFunction2() {
document.getElementById("myDropdown").classList.toggle("show");
}
function myFunction3() {
document.getElementById("languageslist").classList.toggle("show");

}
</script>
</body>
</html>

Answer

This is because you are not hiding the submenu at initial stage.

Add a class to languagelist & hide it. On click of it toggle the class

HTML

<div id = "languageslist" class="hide"> // add a class here
        <a href="">English</a>
        <a href="">Spanish</a>
        <a href="">German</a>
        </div>

JS

function myFunction3() {
    document.getElementById("languageslist").classList.toggle("hide");
    document.getElementById("languageslist").classList.toggle("show");
}

JSFIDDLE