Several dropdown menus within the same container, working independently of each other

I recently encountered an issue with a drop-down navigation bar. When I have multiple drop-downs and click on one, it opens as expected. However, if I then proceed to click on another drop-down while the first one is already open, both of them remain open simultaneously. This behavior is not desired, so I am seeking guidance on how to resolve this problem.

Below is the code snippet that I am currently working with:

HTML:

<nav class="navbar">
    <ul class="navbar-links">
        <li class="navbar-link"><a href="#">Home</a></li>
        <li class="navbar-link"><a href="#">About</a></li>
        <li class="navbar-link dropdown">
            <a href="#">
                Projects
                <i class="fa fa-caret-down" aria-hidden="true"></i>
            </a>
            <div class="dropdown-content">
                <a href="#">Shanary</a>
                <a href="#">Physics Solver</a>
                <a href="#">A simple blog</a>
            </div>
        </li>
        <li class="navbar-link dropdown">
            <a href="#">
                Projects
                <i class="fa fa-caret-down" aria-hidden="true"></i>
            </a>
            <div class="dropdown-content">
                <a href="#">Something else</a>
                <a href="#">Text Editor</a>
                <a href="#">A social Network</a>
            </div>
        </li>
    </ul>
</nav>

CSS:

.navbar {
    background-color: #3A506B;
    border-bottom: 1px solid #cccccc;
    box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
}
.navbar-links {
    margin: 0;
    font-size: 16px;
    list-style-type: none;
}
.navbar-link,
.dropdown-content a {
    display: inline-block;
    padding: 20px 0px;
    transition: background 0.1s ease-in-out;
}
.navbar-link:hover,
.dropdown-content a:hover {
    background: #3f5775;
}
.navbar-link a {
    padding: 20px 10px;
    color: #5DD39E;
    text-decoration: none;
}
.dropdown {
    position: relative;
    display: inline-block;
}
.dropdown-content {
    display: none;
    position: absolute;
    top: 100%;
    min-width: 160px;
    padding: 10px;
    z-index: 1;
    background-color: #3A506B;
}
.dropdown-content a {
    display: block;
}
body {
    font-family: 'Open Sans', Arial, sans-serif;
    background: #FFFFFF;
    color: #16302B;
    margin: 0px;
}
.visible {
    display: block;
}

This is the JavaScript function I have implemented so far:

$('.dropdown').click(function() {
    $(this).find('.dropdown-content').toggleClass('visible');
});

To view the JSFiddle demonstration, click here.

The issue persists in which both drop-downs remain open simultaneously without closing each other. Here is an illustration of the problem:

https://i.sstatic.net/lc3fb.png

Answer №1

In order to identify the current target and remove its visibility, it is essential to iterate through all targets.

Check out the code snippet below:

$('.dropdown').click(function(e) {
  $(this).find('.dropdown-content').toggleClass('visible');
  var currentTarget = this;
  $('.dropdown').each(function() {
    if (currentTarget != this) {
      $(this).find('.dropdown-content').removeClass('visible');
    }
  })
});
.navbar {
  background-color: #3A506B;
  border-bottom: 1px solid #cccccc;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
}

.navbar-links {
  margin: 0;
  font-size: 16px;
  list-style-type: none;
}

.navbar-link,
.dropdown-content a {
  display: inline-block;
  padding: 20px 0px;
  transition: background 0.1s ease-in-out;
}

.navbar-link:hover,
.dropdown-content a:hover {
  background: #3f5775;
}

.navbar-link a {
  padding: 20px 10px;
  color: #5DD39E;
  text-decoration: none;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  top: 100%;
  min-width: 160px;
  padding: 10px;
  z-index: 1;
  background-color: #3A506B;
}

.dropdown-content a {
  display: block;
}

body {
  font-family: 'Open Sans', Arial, sans-serif;
  background: #FFFFFF;
  color: #16302B;
  margin: 0px;
}

.visible {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar">
  <ul class="navbar-links">
...

</div>
</div>
</div></answer1>
<exanswer1><div class="answer accepted" i="43574618" l="3.0" c="1492959654" m="1492970801" v="1" a="cmVwemVybw==" ai="3874768">
<p>You will have to loop through all targets to determine whether they are the current target or not and remove visibility</p>

<p>See snippet below</p>

<div>
<pre class="lang-js"><code>$('.dropdown').click(function(e) {
  $(this).find('.dropdown-content').toggleClass('visible');
  var that = this;
  $('.dropdown').each(function() {
    if (that != this) {
      $(this).find('.dropdown-content').removeClass('visible');
    }
  })
});
.navbar {
  background-color: #3A506B;
  border-bottom: 1px solid #cccccc;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.2);
}

.navbar-links {
  margin: 0;
  font-size: 16px;
  list-style-type: none;
}

.navbar-link,
.dropdown-content a {
  display: inline-block;
  padding: 20px 0px;
  transition: background 0.1s ease-in-out;
}

.navbar-link:hover,
.dropdown-content a:hover {
  background: #3f5775;
}

.navbar-link a {
  padding: 20px 10px;
  color: #5DD39E;
  text-decoration: none;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  top: 100%;
  min-width: 160px;
  padding: 10px;
  z-index: 1;
  background-color: #3A506B;
}

.dropdown-content a {
  display: block;
}

body {
  font-family: 'Open Sans', Arial, sans-serif;
  background: #FFFFFF;
  color: #16302B;
  margin: 0px;
}

.visible {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar">
  <ul class="navbar-links">
    <li class="navbar-link"><a href="#">Home</a></li>
    <li class="navbar-link"><a href="#">About</a></li>
    <li class="navbar-link dropdown">
      <a href="#">
            Projects
            <i class="fa fa-caret-down" aria-hidden="true"></i>
            </a>
      <div class="dropdown-content">
        <a href="#">Shanary</a>
        <a href="#">Physics Solver</a>
        <a href="#">A simple blog</a>
      </div>
    </li>
    <li class="navbar-link dropdown">
      <a href="#">
            Projects
            <i class="fa fa-caret-down" aria-hidden="true"></i>
            </a>
      <div class="dropdown-content">
        <a href="#">Something else</a>
        <a href="#">Text Editor</a>
        <a href="#">A social Network</a>
      </div>
    </li>
  </ul>
</nav>

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

Incorporating the JqueryUI menu into an AngularJS project

We are facing an issue with integrating JqueryUI menus into our AngularJS application. In our Layout.js file, we are attempting the following: OURApp.controller('leftBarCtrl', ['$scope', function ($scope) { $scope.init = function ( ...

Updating Sailsjs Localization Settings

After working with Sails.js for a while, I am interested in finding out if it is possible to manually adjust the localization from the controllers based on the URL. For example, accessing http://example.com/en would display the English version, while http ...

Iterating Through Multiple Dimensions

I am facing a challenge with creating rules from three arrays that I have. The task is to generate every possible combination of entries from each array, but I am struggling with the logic required to write a function for this purpose. For example: var ar ...

Learn how to securely transmit data using basic authentication in Node.js with the node-fetch module

Having trouble with this code. I am facing an issue where a "post" request with basic authentication returns a 200 status, but no response data is received. Surprisingly, when the same code is executed without auth credentials, it works perfectly fine. l ...

Is there a way to set a default CSS background image using JavaScript in case the specified

When working with regular CSS, I can easily set a fallback image using this code in case the primary image is not available: .container { background-image: url(pics/img.webp), url(pics/img.png); } But when it comes to setting styles in JavaScript (such ...

Split domain names for images using a JQuery plugin

Recently, I came across an interesting article by Stoyan Stefanov on JS domain sharding for image files. After reading it, I felt inspired to enhance the concept and create something new. The script below is designed to go through all the images on a page ...

Identifying CMYK Images Through Javascript Feature Detection

Many are aware that IE8 does not support CMYK JPG images, as it fails to render them at all. This post discusses the issue further: , among others. My inquiry is as follows: Is there a method to detect from JavaScript, akin to Modernizr, whether a browse ...

Submitting an array from jQuery to Django

I'm having trouble sending a jQuery array of simple numbers to Django via POST, and I can't seem to figure out what's going wrong. Any assistance would be greatly appreciated. Currently, I'm encountering an Http 500 error with the messa ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...

Node.js encountering an empty array from an API request

In the 'product.js' file, there seems to be an issue with the API call '/achaar/products/1'. The value of val is empty when logging it in the console. Other API calls like '/achaar/products' are functioning correctly, but spec ...

Tips for building and implementing Angular URL Parameters for URLs in the form: "component/#/?id=..."

I am currently facing a situation where I have an application with an existing user base. I am looking to avoid disrupting their current links for a smoother transition. However, the previous links are in this format: (server)/viewer/#/?id=12. Please see t ...

My goal is to eliminate unnecessary code and transfer it into its own jQuery function

Currently, I am working on optimizing my code by removing redundancies and moving sections to separate functions. //Consolidating Infotypes for filtering and checking if any option is selected if(this.$infoOptions.val() != null){ ...

The React router Link does not update the route after an if statement is executed

I'm in need of some assistance regarding React.js. Despite my efforts to find a solution, nothing has worked for me so far. Here are some examples of what I've searched for: How to use Redirect in the new react-router-dom of Reactjs Redirectin ...

Error: NgFor can only be used to bind to data structures that are iterable, such as Arrays. JSON arrays are

Encountering ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables like Arrays. *ngFor="let spec of vehicleSpecs" Tried various solutions and searched extensi ...

Leverage shared techniques and libraries across two different projects

I have a NodeJS project set up on Firebase cloud functions, with our backend service (ExpressJS) as an HTTP function and some cron functions. The project structure looks like this: /project (the main directory for all cloud functions) - package.json ...

Create a straightforward spinning tool using JQUERY

I recently acquired a JQuery plugin from Google designed to detect a "mousehold" event for JQUERY. $('document').ready(function(){ $('#button').mousehold(function(){ //Implementing a spinner here }); }); The mous ...

Controlling the angular bootstrap modal form with ease

I am having trouble accessing the form in the modal controller (Plunkr). The variable myForm doesn't seem to be accessible. How can I make the alert call work correctly: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCt ...

React is throwing a parsing error due to the incorrect use of braces. Remember, JSX elements must be wrapped in an enclosing tag. If you were trying to include multiple elements without a parent tag, you can use a JSX fragment

Having recently started working with React, I came across this code snippet return ( <div> dropdown ? (<li className='goal-list-item' onClick={() => setDropdown(!dropdown)}>{goal.name}</li>) : ...

What is the best method to transfer information between main.js and a specific directory?

Is there a way to efficiently pass data between the main and directory components? I would like to automatically activate the directive when main.js loads. Directive code: angular.module('dmv.shared.components'). directive('doImportPackag ...

What causes a CSS Variable to appear crossed out in the Chrome Debugger?

Currently facing a challenge with debugging an issue where certain CSS Variables are being overridden by an unknown source. It's puzzling because I cannot identify what is causing the override. When it comes to standard CSS properties (such as font-fa ...