Skip to content Skip to sidebar Skip to footer

Hide The Drop Down Menu When Clicking Outside

I have a dropdown menu with checkboxes inside. I want to close the dropdown when the users click outside. My code is:

Solution 1:

Try using the event.target to handle click events:

UPDATE

$(document).on('click', '.multiselect .selectBox', function(e) {
  e.stopImmediatePropagation();
  $('#checkboxes').show();
});

$('body').on('click', function(e) {  
  if (e.target.id != 'checkboxes' && $(e.target).closest('#checkboxes').length == 0) {
    $('#checkboxes').hide();
  }
});
#checkboxes,
.multiselect {
  padding:15px;
  border:1px solid #d8d8d8;
}

.selectBox { display: inline; }

#checkboxes { display:none }
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><divclass="multiselect"><divclass="selectBox"><select></select></div><divclass="checkboxes"id="checkboxes"><labelid="userName">Employee 1</label><inputclass="checked"type="checkbox"name="search_emp"id="emp_1"value="val_1"><labelid="userName">Employee 1</label><inputclass="checked"type="checkbox"name="search_emp"id="emp_1"value="val_1"></div></div>

Solution 2:

Check if the target click on dom is the dropdown itself or not as

$(document).on("click", function(event){
        var $trigger = $(".checkboxes");
        if($trigger !== event.target && !$trigger.has(event.target).length){
            $(".checkboxes").hide();
        }            
    });

It should work.

Post a Comment for "Hide The Drop Down Menu When Clicking Outside"