Pbalazs89
Pbalazs89

Reputation: 168

Jquery - Conditional dropdown does not stay open

I'm trying to build a dropdown menu.

  1. Opens when clicked on.
  2. Stays open when submenu item is clicked on.
  3. Closes when I click anywhere else on the screen.

  4. Is OK.

  5. Not OK.
  6. Is OK.

I can't find the fault in the logic I used, any help is appreciated!

Thanks!

$

    // Dropdown menu icon animation up/down toggle.

$('.dropbtn').on('click', function() {
  $('#myDropdown').slideToggle();
  $(this).find('i').toggleClass('fa-sort-up fa-sort-down')
});


// Dropdown menu up/down toggle.


$(document).mouseup(function(e) {
  var container = $(".dropdownmenu");
        if (!container.is(e.target) 
      && container.has(e.target).length === 0


       ) 

  {
    $("#myDropdown").slideUp();
    $('.dropbtn i').addClass('fa-sort-up').removeClass('fa-sort-down')
  }
});

HTML

<div class="dropdown">
                  <div class="dropdownmenu">
                    <button class="dropbtn main">Diet or Allergen Filter <i class="fa fa-sort-up" style="font-size:24px; line-height:0px; margin-left: 5px;"></i></button></div>
                    <div id="myDropdown" class="dropdown-content">
                        <a id="veganDiet" class="dropbtn"><img src="http://www.padthai.decorolux.com/wp-content/uploads/2017/11/vegan2-1.png"  style="width:40px; display:inline; height:20px; vertical-align:middle;"> Vegan</a>
                        <a id="vegetarianDietButton" class="dropbtn"><img src="http://www.padthai.decorolux.com/wp-content/uploads/2017/11/vegetarian-1.png" style="width:40px; height:20px; display:inline; vertical-align:middle;"> Vegetarian</a>
                        <a id="noAddesSugarButton" class="dropbtn"><img src="http://www.padthai.decorolux.com/wp-content/uploads/2017/11/sugarfree-1.png" style="width:40px; height:20px; display:inline; vertical-align:middle;"> No Added Sugar</a>
                    </div>
                </div>

Also, here's the live codepen:

https://codepen.io/Pbalazs89/full/ZxQbqY

Upvotes: 0

Views: 40

Answers (1)

Scaramouche
Scaramouche

Reputation: 3257

Here, try this

$(document).mouseup(function(e) {
    //if you are clicking on the a tags inside #myDropdown stop 
    //propagation of the event up the DOM (prevent it from getting to 'document')
    if($(e.target).is('#myDropdown a')){
        e.stopPropagation();
    }else{
        $("#myDropdown").slideUp();
        $('.dropbtn i').addClass('fa-sort-up').removeClass('fa-sort-down')
    }
});

Event propagation works from inside out, when you click an element you trigger its event, then its parent's event and so on; e.stopPropagation() stops that from happening, hence the mouseup event will only get to the document if you are NOT clicking on your #myDropdown a.

Try it and LMK

Upvotes: 1

Related Questions