Using Jquery to attach an event to a particular div which is part of a group of divs sharing

I am trying to implement a mouseup event on a series of divs that, when clicked, will reveal a child div ('menu'). All the parent divs have the same class. Here is an example:

<div class="container">
  <div class="menu"><p>Text</p></div>
</div>
<div class="container">
  <div class="menu"><p>Text</p></div>
</div>
etc...

However, I want the event to only trigger when the specific 'container' is clicked. When I click on another 'container', I want the previously opened 'menu' to hide while revealing the new one. My current solution involves creating variables for each container and giving them unique classes.

  $(document).mouseup (function (e){

   var buttonOne = $(".containerOne");
   var buttonTwo = $(".containerTwo");
   var menuOne = $(".containerOne").find(".menu");
   var menuTwo = $(".containerTwo").find(".menu");

   if(buttonOne.is(e.target)){
     menuOne.toggle(100);
     menuTwo.hide();

   }

   else if(buttonTwo.is(e.target)){
     menuTwo.toggle(100);
     menuOne.hide();
   }

   else {
    $(".menu").hide();
   }
 });

Check out this JSFiddle link for a quick demo.

Doing this for multiple containers results in long lines of code, and I believe there must be a simpler way to achieve this. Sorry if my explanation is unclear, it has been a tiring day!

Answer №1

Include a new class in the containerxxx section and then implement a basic click handler

<div class="containerOne container">
    <div class="menu">
        <p>Text</p>
    </div>
</div>
<div class="containerTwo container">
    <div class="menu">
        <p>Text</p>
    </div>
</div>

subsequently

var $menus = $('.container .menu');
$('.container').mouseup(function (e) {
    var $menu = $(this).find('.menu').toggle();
    $menus.not($menu).hide()
});

Demonstration: Fiddle

Answer №2

What do you think of this solution?

$(".wrapper").on("click", function() {
    var selected = $(".dropdown", this).toggle(150);
    $(".dropdown").not(selected).hide();
});

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

Is it possible for a website to instruct a user's browser to save the entire page locally?

Is it possible for a (single-page) website to instruct a user's browser to save the entire page locally? To provide some background: I am running a website on a server that bills based on bandwidth usage. Since the content of the site remains mostly ...

Creating a custom calculator using Javascript

As a beginner in Javascript, I am seeking assistance in creating a simple calculator that can add numbers as buttons are clicked and display the running total. For example: If I click the button "20," it should display the number 20. Then, if I click the ...

The reducer and the store are experiencing a lack of synchronization

I'm having trouble figuring out what's going on with my json file that contains a list of products. I'm trying to render specific ones, but it's not working as expected. Here's the reducer code I'm using: export default(stat ...

Hover activates a CSS animation where elements pop over other elements

I want to design a menu that resembles those "apps panels" we often see. My menu consists of 6 elements, arranged side-by-side with no space between them. When I hover over an element, it slightly pops as shown in the code snippet below: #account-bub ...

The matMul function encountered an error due to a mismatch in the inner shapes of the Tensors. The shapes provided were 684,1 and 2,1, and the transposeA and transposeB parameters were both set

I am completely new to the world of AI and tensorflow.js. Currently, I am following a Machine Learning course by Stephen Grider. I was expecting an output after running the code below, but instead, I encountered an error. Can someone please assist me? Her ...

Manipulating the Document Object Model (DOM) in Google

I typically implement this method to ensure that users adhere to the validation rules before submitting. <a class="waves-effect waves-light btn disabled">Submit</a> But, I recently discovered that by simply removing the disabled class using G ...

Advancing past the stage of developing basic functions in the document.ready() event handler

When I develop a website, I have a personal preference of creating a main JavaScript file with window.load and window.ready functions at the top. I find it easier to refactor any logic into separate functions within these functions for better readability. ...

grab the destination URL from the embedded frame

Thank you for your attention. I am working with three iframes spread across different HTML documents. Here is how they are organized: In the file iframemain.html, there is: <iframe src="iframeparent.html" width="100%" height="600"> </iframe> ...

Manipulating nested JSON objects with AngularJS by adding and pushing the data

I am looking at a JSON object structured like this : { "Name": "Shivansh", "RollNo": "1", "Stream": "CSE", "OverallScore": "76", "Semester": [ { "SemesterName": "FY-2012 - 1", "TotalScore": "78.00", ...

Change the color of the Parent Menu when a childMenu is clicked on using CSS and HTML

<li class="btn-group" mdbDropdown> <a mdbDropdownToggle id="ParentId"> <i class="nav-item"></i> MainMenu <i class="fa fa-angle-down"></i> </a> <div class=" ...

Using formidable to parse form data in Node.js

Hello everyone, I'm a beginner with node.js and I'm currently working on setting up a file/image upload script. After successfully installing node on my VPS, I came across this helpful guide that assisted me in setting up the app with formidable ...

Eliminate any trace of Bootstrap 4 design elements on the .card-header

I'm facing some difficulties in removing all the default styling of Bootstrap 4 from the .card component. It seems like this issue might not be directly related to Bootstrap since I am also experiencing it in Edge browser. Could someone please assist ...

When I add text to div boxes, they begin to drift downward

After creating four div boxes with content, I encountered an issue. Initially, when inserting filler text, everything seemed fine. However, as soon as I started adding actual content into the first box, the other three boxes shifted downwards by the same a ...

Update the var value based on the specific image being switched using jQuery

I have implemented a jQuery function that successfully swaps images when clicked. However, I am now looking to enhance this functionality by passing a parameter using $.get depending on the image being displayed. Here is the scenario: I have multiple comm ...

When importing both shared-lib and MUI in my ReactJS application, I noticed that my custom MUI styles were being overwritten by the MUI styles

I have developed a shared library using React and Storybook. Within this library, I am utilizing the MUI V5 Button and making some style modifications using CSS modules. I executed the "build&pack" script in my library, which generated a tgz package that ...

The json_encode() function yields an empty result

I am facing an issue with a PHP script that is supposed to parse an array using the json_encode() method, but it returns a blank output. Here is the PHP code snippet: $companies = $db->getCustomerNames(); print_r($companies) if (!empty($companies)){ $ ...

"Enhance Your XYChart with a Striking Background Image Using Amchart

let chart = am4core.create("chartdiv", am4charts.XYChart); chart.background.image = am4core.image("/static/img/bar-chart.png") I'm attempting to apply a background image to my chart in Amchart, but unfortunately it's not di ...

Click to expand for answers to commonly asked questions

Having trouble setting up a FAQs page on my blog and can't seem to get the code right. Check out what I'm trying to do here: http://jsfiddle.net/qwL33/ Everything seems fine but when I click on the first question, both questions open up. Can som ...

jQuery: Retrieve data from a table

I am currently working on using an HTML table as a look-up table. Normally, I would handle this server-side, but in this particular case, the client will be inputting the table. When filling out a form, they provide two values from columns A and B, which t ...

Techniques for preventing background layering using CSS

I have implemented a background image on the <input type="submit"> element to give it the appearance of a button. My CSS code looks like this: input.button { background-image:url(/path/to/image.png); } Furthermore, I would like to display a dif ...