Deactivating one div's class upon clicking on another div

Below is the HTML code snippet:

 <div class="container">
  <ul class="navbar">
    <li class="nb-link"><a>Home</a></li>

    <li class="dropdown">
      <a>CBSE</a>
      <ul class="dropdown-menu">
        <li>10th Standard</li>
        <li>12th Standard</li>
      </ul>
    </li>

    <li class="dropdown">
      <a>Engineering</a>
      <ul class="dropdown-menu">
        <li>JEE - Main</li>
        <li>JEE - Advanced</li>
      </ul>
    </li>
  </ul>

There are two dropdowns included. Clicking on one reveals its content, but clicking on another one while the first remains open causes an overlapping issue. The current JavaScript function to handle this behavior is as follows:

 $(document).ready(function() {
    $('.dropdown').click(function() {
        var $this = $(this);

      if ($this.children('.dropdown-menu').hasClass('open')) {
        $this.removeClass('active');
        $('.navbar').$this.children('.dropdown-menu').removeClass('open');
        $this.children('.dropdown-menu').fadeOut("fast");
      } 

        else {
          $this.addClass('active');
          $this.children('.dropdown-menu').addClass('open');
          $this.children('.dropdown-menu').fadeIn("fast");
        }

    });

});

How can I enhance the JavaScript functionality so that clicking on a new dropdown closes the previous one? Additionally, how can I ensure that clicking anywhere on the page will close all open dropdowns?

Answer №1

Here is a solution you can try out:

$(document).ready(function() {
    $('.dropdown').click(function() {
        var $this = $(this);
        $('.dropdown').not($this).removeClass('active')
        $('.dropdown-menu').not($this.find('.dropdown-menu')).removeClass('open');
        $this.toggleClass('active');
        $this.find('.dropdown-menu').toggleClass('open');
    });
});

View Demo

This function comes in handy when selectors are not the target.

// Function for handling cases where selectors are not the target
function actionwindowclick(e , selector , action){
            if (!$(selector).is(e.target) 
                && $(selector).has(e.target).length === 0) 
            {
            action();
        }
}

You can implement it in a window click event like this:

$(window).on('click', function(e){
     actionwindowclick(e , ".dropdown , .dropdown-menu" , function(){
         $('.dropdown').removeClass('active')
         $('.dropdown-menu').removeClass('open');
     });
});

View Demo

Note: You may need to use event.stopPropagation() when clicking on the .dropdown-menu element itself

$('.dropdown-menu').click(function(e) {
   e.stopPropagation()
});

Answer №2

Here's a suggestion to improve your code:

$(document).ready(function() {<br>
        $('.dropdown').click(function() {<br>
            var $this = $(this);<br>
            $this.children('.dropdown-menu').toggleClass('open');<br>
            if ($this.children('.dropdown-menu').hasClass('open')) {<br>
                $this.removeClass('active');<br>
                $this.children('.dropdown-menu').fadeOut("fast");<br>
            }<br>
            else {<br>
                $this.addClass('active');<br>
                $this.children('.dropdown-menu').fadeIn("fast");<br>
            }<br>
        });<br>
    });

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

The useEffect hook is failing to trigger

Currently, I am attempting to retrieve data from an API using Redux for state management. Despite trying to dispatch the action within the useEffect hook, it does not seem to be functioning properly. I suspect that the issue lies with the dependencies, but ...

Exploring the depths of JavaScript JSON elements

After processing my PHP code, it generates a JSON output that contains multiple entries in the same structure. Here is an example with two entries: { "0": { "campaign_id": "31", "title": "new title", "description": "new descrip ...

Prevent additional functions from running when clicking in Angular 5

I have implemented an Angular material table where each row expands when clicked. In the last cell of the table, I load a component dynamically using ComponentFactory. This loaded component is a dropdown menu. The problem arises when the dropdown menu is ...

Transmit data via AJAX to the RequestBody

Although seemingly simple, this issue has proven to be quite challenging. I am confident that it can be easily resolved, but the solution continues to elude me. Thank you for any assistance you can provide. Here is the code snippet in question : var samp ...

having difficulty applying a border to the popup modal

Currently, I am utilizing a Popup modal component provided by the reactjs-popup library. export default () => ( <Popup trigger={<button className="button"> Guide </button>} modal nested > {(close: any) =&g ...

Securing Credit Card Numbers with Masked Input in Ionic 3

After testing out 3-4 npm modules, I encountered issues with each one when trying to mask my ion-input for Credit Card numbers into groups of 4. Every module had its own errors that prevented me from achieving the desired masking result. I am looking for ...

Node.js with Socket.io causes multiple events to be triggered

Currently, I am in the process of developing a rochambo game using node.js and socket.io. The game works as follows: A player places a bet, which is then sent to all other players. These players can choose a sign and click on 'challenge'. Howeve ...

One way to enhance Razor helpers is by integrating parameters into them

Is there a way to create an HTML Helper similar to @Html.TextBoxFor(model => model.signature) that includes a data-id parameter in the generated input, like shown below? <input type="text" name="signature" data-id="No Signature" /> I understand ...

Using the Google Chrome console, execute a command on each page within a specified website

While browsing a website, I noticed a bug that required me to manually run a JavaScript function each time I navigated to a different page in order for the site to work smoothly. Is there a way to automate this process upon page load? I am using Google C ...

What are some ways I can customize this jQuery :submit selector demonstration?

After reviewing the jQuery example provided here, I am curious about how to adjust the code in order to change the color of a cell only when the value of the submit button within that cell meets certain criteria. For instance: var submitEl = $( ...

What is the best way to add child elements to existing elements?

When it comes to creating elements with jQuery, most of us are familiar with the standard method: jQuery('<div/>', { id: 'foo', href: 'http://google.com', }).appendTo('#mySelector'); However, there ar ...

The combination of AddEventListener in the parent and postMessage in the iframe is ineffective

As I delve into the Stripe documentation to develop a new feature, I have encountered an issue regarding the communication between a webpage and an iframe. The code in index.html: <!DOCTYPE html> <body> parent<br> <iframe src="./ ...

Error loading custom Javascript in MVC 4 view during the first page load

I'm working on an MVC 4 application that utilizes jQuery Mobile. I have my own .JS file where all the functionality is stored. However, when I navigate to a specific view and check the page source, I notice that all scripts files are loaded except fo ...

Tips for boosting the tabindex in a React search result list with ul-li elements

Implementing search results using ul li: <ul className="search-result"> <li tabindex="1">title here...</li> <li tabindex="2">title here...</li> <li tabindex="3">title here... ...

What is the method for breaking a statement within an if statement on Blogger when both the IF and ELSE conditions are met?

I'm making some adjustments to the labels on my blog to ensure that each post has at least two labels. The concept is that if a post has LABEL 1, it will load one script, otherwise it will load another. However, I've encountered a situation wher ...

Improving iframe functionality in AngularJS

I've been experimenting with AngularJS to dynamically update an iframe whenever a query is triggered. It works like this: a query is made, the embed link is fetched from the database, and then it's used in the iframe alongside the title and video ...

The interaction between jQuery and Rails through ajax calls

Attempting to work with basic functionality, Sending a request with data and receiving a response with data, then displaying it using jQuery and Rails This piece of code pertains to the frontend. $("#internal_btn").click(function() { //windo ...

What is the syntax for using escape characters in Vue?

Looking to create a website similar to CodePen? I have developed a library of assets including buttons, cards, and effects, all built using vue.js. Each asset includes HTML, CSS, and sometimes JS code. In my vanilla JS version, I formatted the code using e ...

When I attempt to return an object from a function and pass the reference to a prop, TypeScript throws an error. However, the error does not occur if the object is directly placed in

Currently, I have the following code block: const getDataForChart = () => { const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; const test = { ...

Eliminate the ArrayOfObjects by filtering out the items with a specific ID

Here is an array of objects I've named mycart[]: [{"id":"6","quantity":"20","price":1500,"title":"casual blue strip"}, {"id":"10","quantity":"2","price":1500,"title":"casual blue round neck"},{"id":"5","quantity":20,"price":150,"title":"casual ...