Paul Paul - 1 year ago 62
CSS Question

Hiding a div when clicking out of it

I added code to make a div,

, close when clicking outside of it. This works fine, but now when clicking on my image div,
, 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 (! // if the target of the click isn't the container...
&& container.has( === 0) // ... nor a descendant of the container
else if (friend_icon.has( {

//Toggle Pending Friend List
$("#friend-icon").click(function() {

#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=""></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 id="pending-friend-list-dropdown">

Answer Source

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:


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

    if ( $( ) // clicking on the toggler-div or the img it contains
    else if (!$( // clicking outside of the toggler
    && !$( // and outside of the toggled div itself

Here's a jsfiddle: