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:

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

How to specify columns when storing data in a CSV file using Scrapy

As I scrape data from the web, I am facing an issue with my csv file where the links column is always displayed as the first column. How can I specify the placement of columns in the csv file? pName = response.css('#search .a-size-medium') ...

Having trouble with a broken link on your HTML email button?

I'm attempting to add a button to an HTML email that redirects to a link within an href tag. Admittedly, my knowledge of html code is minimal. Here's what I've attempted: <p> <input style="width: 200px; padding: 15px; box-shadow: ...

Prevent users from adding or removing any letters

Exploring the ACE Editor integration with AngularJS (utilizing UI-Ace). I have a question. Is it possible to limit the user's actions to: Only allow entering a predefined character (for example, ;) Prevent deletion of any characters except for the p ...

The total sum of values within labels that share the same class

I am attempting to sum up all the values of class tmpcpa and store the result in final_cpa, but for some reason final_cpa always ends up being 0. document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmp ...

Mysterious additional spacing

I am facing an issue with aligning my div elements with a 20px margin. Despite setting the margin to 20px, I notice that there are additional 4 pixels rendered when I view it on the browser. Below is the code snippet: .block{ width:50px; height:50 ...

Is there a way to update a child component in React when the parent state changes, without utilizing the componentWill

I am currently working on developing a JSON editor using React, but I am facing an issue with the library I am utilizing not having a componentWillReceiveProps hook. As someone relatively new to React, I am trying to find a way to automatically update th ...

What is the process for running a continuous stream listener in a node.js function?

I am currently working with a file called stream.ts: require('envkey') import Twitter from 'twitter-lite'; const mainFn = async () => { const client = new Twitter({ consumer_key: process.env['TWITTER_CONSUMER_KEY'], ...

After the loop completes, only the last row is inserted

Here is the issue I am facing with my info.php file. I am extracting the steam_id from the scammers table in this file. The problem arises when I display the results on the front page because all player parameters turn out to be the same. This happens beca ...

Choose an option from the dropdown menu using a variable

I've been struggling to get a dropdown's selected value to change based on a query result. No matter what I do, it always defaults to the first option. After searching through numerous similar questions, none of the solutions seem to work for me ...

Tips for positioning Material Ui buttons beside a list of images

I have a list of images and I would like to display buttons beneath each image Here is my current code: export const Media = (stuff) => { const { medias } = stuff; console.log(medias); const classes = useStyles(); return ( <div classNam ...

Issue locating the prettyPhoto() function in ASP.net Jquery

I've been stuck on this issue for a while, so I thought I'd reach out to someone with more expertise. I'm working on a .NET website and trying to implement the prettyPhoto Jquery plugin. I have included the Jquery main library and the Pretty ...

Using jQuery to create a div that animates when scrolling

Recently, I came across this interesting code snippet: $(document).ready(function(){ $(window).scroll(function(){ if($("#1").offset().top < $(window).scrollTop()); $("#1").animate({"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fix ...

Personalize the tooltip feature in highchart

I am looking to enhance the tooltip feature in HighChart. Currently, on hover of my bar chart, only one value is displayed in the tooltip. However, I would like to display three values instead. Here is a snippet of my code: $(function () { $( ...

Reverse animation transition not activating in CSS

In an attempt to create a side navbar using HTML/CSS, I implemented hover animations where hovering over an icon would cause it to double in size and disperse the rest of the items in the navbar. While I successfully achieved this animation with JavaScript ...

How to Show an Image in a Search Bar Using HTML

As I put the finishing touches on this table, I decided to add a search function to it. However, I encountered an issue with the search bar design. I wanted to incorporate a search icon png file as the background image, similar to the example showcased on ...

Guide on replacing buttons with <a> tags in express.js posts

I've incorporated handlebars as my chosen templating engine and I'm utilizing buttons to trigger app.post() in my JavaScript file. <form method="POST" action="/smo_assessment"> <div class="container" id="div1"> <h3 id="header" ...

Several features - Second function malfunctioning

The initial inquiry is effective. However, the subsequent one is encountering issues as it is failing to confirm if an email contains the "@" symbol. My attempted solution involved reordering the functions related to email validation. <body onload="ch ...

Is there a way to automatically add a div to the window as the user scrolls and then hide the div when they scroll back to the

Seeking assistance with creating a function that will add a 'sticky' class to the menu when the user scrolls down to the middle, and then append a div when the 'sticky' class is present. Currently facing issues where the div keeps appen ...

Unable to update the numerical value in the Material-UI version 5 TextField component

When attempting to display the decimal value 1.0 in the MUI5's TextField component, I encountered an issue. While I can change its value using the icons within the TextField, inputting any value directly seems to be ineffective. Additionally, backspac ...

The next.js router will update the URL without actually navigating to a new page, meaning that it will still display the current page with the updated URL

My search results are displayed at the route /discovery, and I am working on syncing the search state with URL query parameters. For example, if a user searches for "chicken," the URL becomes /discovery?query=chicken&page=1. When a user clicks on a se ...