Reputation: 125
My div opens with a button and that button has two classes (active or not), I want to change the class when I click on the boby and that works, but when I click again on the button the class is misted.
I've searched a lot but I just found to change the class or close the div on body click, can you help me to combine the two of them?
Please, Thanks!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TEST</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
</head>
<style>
body{background:#1E1E1E;}
.link{background:gray;color:black;}
.link_active{background:green;color:white;}
#content{background:gray;border:1px solid;width:100px;height:100px;display:none;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(".link").toggle(function(){
$(this).toggleClass("link_active");
},
function () {
$(this).removeClass("active");
});
$(".link").click(function(){
$(this).next("#content").slideToggle("fast");
$(this).removeClass("active");
});
$(document).on('click', function() {
$('#content').css("display","none");
$('.link').removeClass("link_active");
$('.link').addClass("link");
});
});
</script>
<body>
<a href="#" class="link">OPEN</a>
<div id="content"> content content content content content content</div>
</body>
</html>
Upvotes: 1
Views: 2077
Reputation: 9370
See this: http://jsfiddle.net/LVfdk/2/
$(document).ready(function () {
$(".link").click(function (e) {
$(this).next("#content").slideToggle("fast");
$(this).toggleClass("link_active");
e.stopPropagation();
});
$(document).on('click', function (e) {
if (e.target.id !== "content") {
$('#content').css("display", "none");
$('.link').removeClass("link_active");
$('.link').addClass("link");
}
});
});
Upvotes: 2
Reputation: 4617
$(document).on('click', function() {
$('#content').toggle();
$('.link').toggleClass("link_active link");
});
Upvotes: 0