I've just begun to learn JavaScript.
I wrote a simple dropdown menu, but when you initially load the page, two clicks on the "dropdown"- button (with onclick attribute) are required for the link list to be displayed.
After that, it works as intended - you only need to click one time on the button to display/hide the list.
But why do I have to click two times on the button after intially loading the site?
Here's my HTML/CSS:
#dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
#dropdown {
position: relative ;
display: inline-block;
}
#dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
#dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
#dropdown-content a:hover {background-color: #f1f1f1}
/*#dropdown:hover #dropdown-content {
display: block;
}*/
#dropdown:hover #dropbtn {
background-color: #3e8e41;
}
<h2>Dropdown Menu</h2>
<p>Just a simple menu with link list</p>
<div id="dropdown">
<button id="dropbtn" onclick="myFunction()">Dropdown</button>
<div id="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
<script>
function myFunction() {
if (document.getElementById('dropdown-content').style.display == "none")
{document.getElementById('dropdown-content').style.display = "block";}
else {document.getElementById('dropdown-content').style.display = "none";}
}
</script>