Navigation Bar Dropdown Menu Not Responding to Clicks

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! :)

Answer №1

Do you need something similar to this? The desired functionality is already working, I just added some CSS for better styling.

.show 
{
  display:block;
  width: 245px; 
  right: 0; 
  left: auto;
  line-height: 30px;
  overflow: hidden
}

By adding height: auto to the ul and removing overflow: hidden from the parent of ul, you can achieve the desired result: Check it out here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Plugin for webpack that replaces a specified function with an alternative one

I'm currently working on a webpack plugin that has the ability to analyze code and replace a particular function with another function. Additionally, this plugin will make the new function accessible globally. class PluginName { constructor(local, ...

Instructions on filling the star icon with color upon clicking the button

Currently working on a project using codeIgniter where I have a form for rating products. I am facing an issue where, upon clicking the star button, only the border color changes to yellow while the center of the button remains white. Can someone please g ...

Border extends across two separate rows

Let me illustrate my issue with a specific example where I am utilizing a single column with a rowspan: <table border="1" style="width:300px"> <tr> <td rowspan="2">Family</td> <td id="jill">Jill</td> <td>Smi ...

The positioning of the <thead> element does not seem to be functioning properly

I attempted to create a background for the header (thead) using a pseudo element (:after) because I wanted the background to span from one edge to another edge (including both left and right side padding). However, thead is not taking a relative position a ...

Executing Code from Tab only upon tab activation

I have multiple tabs on my page, and I want to have one tab with a widget that only loads when the user clicks on it, instead of loading along with all other tabs when the page loads. <div class="tabbable tabbable-custom"> <ul class="nav nav-t ...

Is there a way to embed HTML code within a JavaScript variable?

Embedding HTML code within Java Flow can be quite interesting For instance: Check out this JSFiddle link And here's how you can incorporate it into your script: widget.value += ""; Generating a Pro Roseic Facebook POP-UP Box through Widg ...

Ways of converting a negative lookbehind into an ES5-friendly expression

In my code, I have a RegExp that works perfectly, but it only functions with ES2018 due to its use of negative lookbehinds. The problem is that a library is using this RegExp function, so modifying how it's used is not an option. I attempted to add n ...

Test your word skills with the Jumbled Words Game. Receive an alert when

After reviewing the code for a jumble word game, I noticed that it checks each alphabet individually and locks it if correct. However, I would like to modify it so that the entire word is only locked if all the letters are correct. Any suggestions on how t ...

"Trying to refresh your chart.js chart with updated data?”

Greetings! I have implemented a chart using chart.js and here is the corresponding code: let myChart = document.getElementById('myChart').getContext('2d'); let newChart = new Chart(myChart, { type: 'line', data: { labels: ...

Mastering the use of expressions in ng-click and ng-show in AngularJS

I've been working on creating expandable rows within a table, but I'm encountering some issues. Despite not receiving any error messages, the functionality isn't behaving as expected. I suspect there might be an issue with how I'm using ...

The error message reads: `'Icon' is not included in the export list of 'antd'`

I have recently developed a React application and I'm incorporating Ant Design (antd) into it. However, I encountered an issue in one of my project files where I am unable to use the Icon tag. It seems like this is a known problem in ANT V4. The impo ...

Manipulating the size of one div automatically adjusts the size of the other, as they are

I have encountered an issue while trying to manage two resizable divs. I am looking for a solution where changing the size of one div will automatically adjust the size of the other div along the grid, and vice versa. Currently, I am only able to achieve ...

Arranging various s:select dropdowns for inline display styling

I have a form with three consecutive struts2 tags. Upon rendering the page, the s:select tag is automatically converted to the HTML code at the bottom. The issue arises when I attempt to style the form in order to display these dropdowns horizontally. Unf ...

Show product name when hovering over the image

Trying to achieve a hover effect where product titles appear in a contained box when hovering over the product image on the bottom overlay, instead of below the image itself. Tried CSS code recommended by Shopify, but it had no effect: <noscript> ...

A step-by-step guide on uploading a CSV file in Angular 13 and troubleshooting the error with the application name "my

I am currently learning angular. I've generated a csv file for uploading using the code above, but when I try to display it, the screen remains blank with no content shown. The page is empty and nothing is displaying Could it be that it's not ...

"Executing the command 'npm run dev' is successful, however, the command 'next dev' does not yield the expected result

Trying out Next for the first time using npx create-next-app, but running into issues with the scripts. While npm run dev works without any problems, executing next dev gives me an error saying zsh: command not found: next. Any idea why this is happening? ...

What is the best way to run a JavaScript function once another function has finished executing?

I am looking to ensure that a JavaScript function runs only after another one has finished executing. Here is the code I currently have: $(window).load(function(){ $('#dvLoading').fadeOut(2000); }); window.addLoadEvent = function() { $('#p ...

When transmitting an ajax POST FormData object, the key and value may not be transmitted as originally configured

In my code, I am setting up a FormData object like this: const formData = new FormData(); formData.append('id', '12345678'); Next, I make a POST request using angular HttpClient. However, when I use Postman to debug the reques ...

Setting the transition time for adding or removing components in ReactJS CSS

As the list component changes in size based on its children, it tends to move around abruptly. Applying transition: 'all 0.3s ease' doesn't resolve this issue since it's the layout that is affected by the number of children rather than ...

Is it possible to extract the selected indexes of all select menus in my HTML and assign them to various arrays of my choosing? I find myself writing a lot of code just for one select menu

In order to determine which TV character the user most closely resembles based on their answers to a series of questions, I have created a function. However, my current code is inefficient when it comes to handling multiple select menus! I am considering i ...