natsu1627
natsu1627

Reputation: 74

Toggle div when clicked and hide when clicked outside

I already have my code to toggle show and hide the div but whenever I try to add the Hide when clicked outside, it conflicts the toggle code, I need to toggle the div_menu but also hides it when clicked outside just like the facebook drop down menu

$(document).ready(function() {
    $(".toggle_menu").click(function(e) {
        $(".div_menu").toggle();
        e.preventDefault();
    });
});

Upvotes: 1

Views: 2884

Answers (5)

Casey Rule
Casey Rule

Reputation: 2085

$(document).ready(function() {
    $(".toggle_menu").click(function(e) {
        $(".div_menu").toggle();
        e.preventDefault();
    });
    $(document).click(function(e) {
        $(".div_menu").hide();
    });
});

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

use e.target to find the current targeted element ,and using is() Check the current matched set of elements against a selector

$(document).ready(function () {
    $(document).click(function (e) {
        if ($(e.target).closest(".toggle_menu,.div_menu").length) {
            $(".div_menu").toggle();
            e.preventDefault();
        } else {
            $(".div_menu").hide();
        }

    });
});

DEMO

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

You can do something like

$(document).ready(function () {
    $(".toggle_menu").click(function (e) {
        $(".div_menu").toggle();
        e.preventDefault();
    });
    $(document).click(function(e){
        if(!$(e.target).closest('.toggle_menu, .div_menu').length){
            $(".div_menu").hide();
        }
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="toggle_menu">toggle_menu</button>
<div class="div_menu">
  <div>some random content menu</div>
</div>
<div style="height: 100px; background: lightgrey;">some other content goes here</div>

Upvotes: 4

Cerlin
Cerlin

Reputation: 6722

try this

$(document).click(function(e){
    if($(e.target).parents('.div_menu').length == 0 && $(e.target).attr('class') != "div_menu"){
        $(".div_menu").toggle();
    }
});

Upvotes: 0

Ravin Sardal
Ravin Sardal

Reputation: 727

$("body").click
(
   function(e){
      if ($(e.target).is($(".toggle_menu"))) {
        $(".div_menu").toggle();
      }else{
        $(".div_menu").hide();
      }
   }
);

Upvotes: 0

Related Questions