Adam Pavlov
Adam Pavlov

Reputation: 307

Click outside hide element

When I click on "Menu", ".submenu" toggle, I need when I click outside then ".submenu" should hide. I have used this in every div as like rows as like we use in app where it place at right side for edit delete. Thanks in advance.

HTML :

<div class="edit-goal-wrapper">
                        <div class="dropdown">
                            <a class="account" >Menu</a>
                            <div class="submenu">
                                <ul class="root">
                                    <li ><a href="#" >Edit Target Date</a></li>
                                    <li ><a href="#" >Remove Goal</a></li>
                                </ul>
                            </div>
                        </div>
                    </div>

CSS :

.edit-goal-wrapper .dropdown
{
    color: #555;
    margin: 0;

    right: 30px;
    text-align: left;
}
.edit-goal-wrapper .submenu
{
    background: #fff none repeat scroll 0 0;
    border-radius: 6px;
    -webkit-box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
    -moz-box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
    position: absolute;
    right: 5px;
    top: 0px;
    z-index: 100;
    width:150px;
    display:none;
}
.edit-goal-wrapper .dropdown li a
{
color: #555555;
display: block;
font-family: arial;
font-weight: normal;
padding: 6px 15px;
cursor: pointer;
text-decoration:none;
}

.edit-goal-wrapper .dropdown li a:hover
{
background:#155FB0;
color: #FFFFFF;
text-decoration: none;
}
.edit-goal-wrapper a.account 
{
    background: rgba(0, 0, 0, 0) url("icons/arrow.png") no-repeat scroll 116px 17px;
    color: #555;
    cursor: pointer;
    display: block;
    font-size: 30px;
    /*height: 28px;*/

    text-decoration: none;
    z-index: 110;

}
.edit-goal-wrapper .root
{
border-top: 1px solid #dedede;
    font-size: 12px; font-weight:normal;
    list-style: outside none none;
    margin: 0;
    padding: 4px 0 2px;
}

jQuery :

$(".edit-goal-wrapper a").click(function(){

                    $(this).next().toggle();

                });

Upvotes: 1

Views: 72

Answers (1)

madalinivascu
madalinivascu

Reputation: 32354

If you want to hide the submenu when you click outside of it try:

$("body").click(function(e){
       if($('.submenu').find(e.target).length  == 0 && $(e.target).is(":not('.account')")) {
          $('.submenu').hide();
       } 
});

jsfiddle:https://jsfiddle.net/z134L2ab/2/

or

$("body").click(function(e){
        if ($(e.target).is('.account')) {
           $('.submenu').toggle();
        } else if($('.submenu').find(e.target).length  == 0) {
           $('.submenu').hide();
        }
});

jsfiddle:https://jsfiddle.net/z134L2ab/3/

Upvotes: 1

Related Questions