I'm having trouble implementing a dropdown menu in my navigation bar that should appear when the user clicks and disappear when they click anywhere outside of it, similar to Facebook's dropdown menu with options like logout. However, for some reason, the dropdown isn't functioning as expected. I've searched extensively on StackOverflow and other online resources but haven't been able to find a solution. I would like to achieve this using only CSS and JavaScript because I'm not familiar with jQuery or other languages.
Here is the link to my code on JSFiddle: https://jsfiddle.net/8ahy32yn/9/
The HTML and CSS code snippets I've implemented are shown below:
HTML
<div id="navbar">
<ul>
<li>
<a href="movies.php">Home</a>
</li>
<li>
<a href="faq.php">FAQs</a>
</li>
<li class="user" style="float:right;">
<a href="#" class="dropbtn" onclick="UserDropdown()">Dropdown</a>
<ul id="UserContent" class="user-content">
<li>
<a href="profile.php">Profile</a>
</li>
<li>
<a href="gifts.php">My Gifts</a></li>
<li>
<a href="logout.php">Logout</a>
</li>
</ul>
</li>
</ul>
CSS
ul
{
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: black;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 55px;
}
li
{
float: left;
}
li a
{
text-decoration: none;
display: block;
padding: 20px 25px;
color: white;
text-align: center;
}
li a:hover
{
background-color: #333333;
}
.user
{
position: relative;
display: inline;
}
.dropbtn
{
cursor: pointer;
}
.user-content
{
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 100px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.user-content a
{
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.user-content a:hover
{
background-color: #F1F1F1;
}
.show
{
display:block;
}
JavaScript
function UserDropdown() {
document.getElementById("UserContent").classList.toggle("show");
}
window.onclick = function(event)
{
if (!event.target.matches('.dropbtn'))
{
var dropdowns = document.getElementsByClassName("user-content");
var i;
for (i = 0; i < dropdowns.length; i++)
{
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show'))
{
openDropdown.classList.remove('show');
}
}
}
}
Unfortunately, the dropdown doesn't show up in the Fiddle when clicked, although it does work on my localhost as intended:
https://i.stack.imgur.com/4a24u.png
Any assistance with this issue would be greatly appreciated. Thanks! :)