Paul Paul - 8 days ago 6
CSS Question

Hiding a div when clicking out of it

I added code to make a div,

#pending-friend-list-dropdown
, close when clicking outside of it. This works fine, but now when clicking on my image div,
friend-icon
, the drop-down div will not close now.

As you can see in my snippet, the image div is what opens the drop-down box. I am just trying to figure out how that image div can be used to open and close the drop-down, while using the mouseup function to close the drop-down div as well.



//Hiding Pending Friend Drop-down when clicking out of it
$(document).mouseup(function (e)
{
var container = $("#pending-friend-list-dropdown");
var friend_icon = $("#friend-icon");

if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
else if (friend_icon.has(e.target)) {
container.hide();
}
});

//Toggle Pending Friend List
$("#friend-icon").click(function() {
$('#pending-friend-list-dropdown').toggle(100);
});

#main-bar {
width: 85%;
height: 60px;
position: relative;
margin-left: 15%;
background: red;
padding: 3px 0;
}
#main-bar-container {
border: 1px solid black;
margin: 0 10px;
position: relative;
width: 95%;
height: 56px;
left: 2%;
}
/*---- Pending Friends List----*/
#friend-icon {
display: inline-block;
cursor: pointer;
position: absolute;
right: 20%;
top: 15px;
}
#friend-icon img {
height: 30px;
width: 30px;
}
#pending-friend-list-dropdown {
height: 500px;
width: 400px;
overflow: scroll;
z-index: 100000;
position: absolute;
left: 70%;
top: 70px;
background: blue;
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-bar">
<div id="main-bar-container">
<div id="friend-icon"><img src="../icons/collection/social.png" alt="Pending Friends"></div>
</div>
</div>
<div id="pending-friend-list-dropdown">
</div>




Answer

You can achieve this more simply by running the code whenever someone clicks on the html-element (the entire page). Then check if the click is located on certain elements.

There is also no need to give the instructions in two places for what to be done when clicking on "#friend-icon". I have removed the second instance of this in the below code, and just moved the .toggle up to the if statement.

It now works like a charm:

$("html").click(function(event) 
{

var container = "#pending-friend-list-dropdown";
var friend_icon = '#friend-icon, #friend-icon img';

    if ( $(event.target).is(friend_icon) ) // clicking on the toggler-div or the img it contains
    {    
        $(container).toggle(100);
    }
    else if (!$(event.target).is(friend_icon) // clicking outside of the toggler
    && !$(event.target).is(container)) // and outside of the toggled div itself
    {
        $(container).hide();   
    }
});

Here's a jsfiddle: https://jsfiddle.net/r54ardcz/2/