JoeDoe
JoeDoe

Reputation: 37

Hide div when click outside the area with jQuery

I would like to hide div content when clicking outside of it. I read a lot of topics on the subject but I can't make it work.

Here is the div I want to hide :

<div class="menu_content">
    <div class="container-fluid">
        <div class="container">
            <div class="row">
                <div class="col-lg-4">
                    <h1>Title</h1>
                </div>
                <div class="col-lg-4">
                    <h1>Title</h1>
                </div>      
                <div class="col-lg-4">
                    <h1>Title</h1>
                </div>
            </div>  <!-- END ROW-->
        </div>
    </div><!-- END CONTAINER FLUID-->
</div>

I'm not an expert in Javascript, so if you have simple sample code to achieve this, it could be great.

I tried the following code but it does not work :

$(document).click(function() {
    if($(this) != $(".menu_main_content")) {
        $(".menu_main_content").hide();
    }
});

Here is the html of the code that opens the DIV content :

 <div class="menu_main_button">
        <img href=""src="{{ asset('images/icons/icon_menu_home.png') }}"  alt="" />
</div>

The button opens the DIV with .menu_main_content class.

So the fact of clicking on the button is considered as outside the DIV. That's my problem.

Thanks in advance for your help

Upvotes: 0

Views: 3071

Answers (2)

Shikkediel
Shikkediel

Reputation: 5205

This is probably one for e.stopPropagation :

Demo

$(document).click(function(e) {

  $('.menu_content').hide();
});

$('.menu_content').click(function(e) {

  e.stopPropagation();
});

Upvotes: 1

Streetlamp
Streetlamp

Reputation: 1556

$(this) always refers to document and I think you can't compare elements like that. Try checking if the given element is hovered, if not, hide it:

$(document).click(function() {
    if (!$(".menu_main_content").is(":hover")) {
        $(".menu_main_content").hide();
    }
});

Upvotes: 0

Related Questions