Jquery - Adding event to specific div that shares class name with others

I'm looking to add a mouseup event to a series of divs, that when clicked, reveal a child div ('menu'). All the parent divs share the same class, for 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'd like the event to only trigger when I've clicked that particular 'container'. When I click on another 'container', I'd like the same thing to happen, however, I'd also like the previously opened 'menu' to hide. The only way I have managed to do this (being a JQuery noob), is to create variables for each container, as well as giving them unique classes. For example:

  $(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();
   }
 });

Quick JSFiddle

This then creates lines and lines of code the more containers I add, and I feel there is almost certainly an easier way of doing this. Apologies if this was written poorly, it's been a long day, ha.

Answers


Add a new class to the containerxxx element then use a simple 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>

then

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

Demo: Fiddle


How about something like

$(".container").on("click", function() {
    var mine = $(".menu", this).toggle(100);
    $(".menu").not(mine).hide();
});

Need Your Help

Replacing recorded values with Data file - Data driven testing

visual-studio-2013 coded-ui-tests data-driven-tests data-driven

I have recorded a simple Coded UI test from visual Studio 2013. What it does is;