Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Joe Consterdine
13,965 PointsClosing element on click outside - What am I doing wrong here?
Hey guys,
Just doing a quick test on clicking outside an element with jquery, but having some problems.
I'm trying to remove a class on click outside of an element.
The problem appears to be that the 'document' handler is activating at the same time as the span and therefore not working.
I need it so it works after the class has already been added.
Any ideas?
Cheers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>animation</title>
<link rel="stylesheet" href="css/normalize.css" media="screen" title="no title">
<link rel="stylesheet" href="css/main.css" media="screen" title="no title">
</head>
<body>
<ul>
<li class="top-list"><span>Item</span>
<ul class="sub-top">
<li class="sub-list">Item 1</li>
<li class="sub-list">Item 2</li>
<li class="sub-list">Item 3</li>
<li class="sub-list">Item 4</li>
</ul>
</li>
</ul>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
$("span").on("click", function(){
$(".sub-list").toggleClass("show-menu");
});
$(document).on('click', function(event) {
if (!$(event.target).closest('.sub-list').length) {
$(".sub-list").removeClass("show-menu");
}
});
</script>
</body>
</html>
body {
width: 80%;
margin: 0 auto;
}
body > ul {
list-style: none;
padding: 0;
text-align: center;
display: inline-block;
width: 150px;
}
ul {
padding: 0;
}
.top-list {
color: #fff;
text-align: center;
}
span {
display: block;
background: #555;
padding: 1rem 0;
cursor: pointer;
}
.top-list > ul {
background: #777;
}
.sub-list {
opacity: 0;
visibility: hidden;
height: 0;
overflow: hidden;
list-style: none;
transition: 0.25s ease-in-out;
}
.show-menu {
opacity: 1;
visibility: visible;
height: auto;
overflow: visible;
padding: 1rem 0;
}
1 Answer

Hannu Shemeikka
16,799 PointsHi,
Indeed the click-event on document is being called after the click-event on span element. You can disable this feature by adding a event.stopPropagation(); line into your click-handler.
$("span").on("click", function(event) {
event.stopPropagation();
$(".sub-list").toggleClass("show-menu");
});
This article is a nice explanation of this behavior.