Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: how to make div disappear when click outside [duplicate]

Tags:

jquery

I tried Chinnu R's approach, but when I click anywhere outside the div, menu items not hiding, only when I click inside the div, menu items hide, I want the opposite, ie, click outside div, hide, click inside div, stay put.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

<script>
$(document).ready(function() {
        $("button").click(function() {
            $('div#nomore').toggle();
        });


        $("body > *").not("body > button").click(function(e) {
            $('div#nomore').hide();
        });
    });

</script>

</head>
<body>
<button>MENU</button>
<div id="nomore" style="display:none; background-color:yellow; width:300px;">
<br>
<a href="www.yahoo.com">Yahoo</a><br>
ITEM 2<br>
ITEM 3<br>
ITEM 4<br>
ITEM 5<br>
</div>
</body>
</html>
like image 531
Cindy Turlington Avatar asked Oct 28 '25 07:10

Cindy Turlington


1 Answers

Can you try this,

        $(document).ready(function() {
            $("button").click(function() {
                $('div#nomore').toggle();
            });

            $("body").click(function(e) {
                 if(e.target.id == "nomore"){
                     $('div#nomore').hide();
                 }
            });
        });

Other method:

        $(document).ready(function() {
            $("button").click(function() {
                $('div#nomore').toggle();
            });         


            $("body > *").not("body > button").click(function(e) {
                $('div#nomore').hide();
            });
        });

Updated code:

            $("body > *").not("body > button").click(function(e) {
                 console.log(e.target.id);
                if(e.target.id=='nomore'){
                        return false;
                 }
                 $('div#nomore').hide();

            });
like image 102
Krish R Avatar answered Oct 30 '25 13:10

Krish R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!