At present, the current code unfolds the DIVs whenever a user clicks on a menu item. This results in the DIV folding and unfolding the same number of times if clicked repeatedly on the same link, without staying closed.
My desired functionality is to have the DIV fold and remain closed when the user clicks on the same menu item for the second time, similar to how it works on a specific website.
Edit: To clarify:
Current behavior:
- Clicking on a navigation menu link opens (unfolds) the associated DIV
- Subsequent clicks on the same link hide (fold) the DIV temporarily before reopening it automatically
Desired behavior:
- Clicking on a navigation menu link opens (unfolds) the associated DIV
- A second click on the same link hides (folds) the DIV and keeps it that way until another click on the same link or a different menu item occurs
How can I implement this? Thank you
View http://jsfiddle.net/u3qtt6fo/5/
JS:
$("a").click(function() {
var page = $(this).data("page");
var active = $(".fold.active");
// if there is visible fold element on page (user already clicked at least once on link)
if(active.length) {
$(".fold.active")
.animate({ width: "0" }, 200 )
.animate({ height: "0" }, 200, function() {
// this happens after above animations are complete
$(this).removeClass("active")
$("#"+page)
.addClass("active")
.animate({ height: "500px" }, 1000, 'linear' )
.animate({ width: "500px" }, 400,'linear' )
})
// clicking for the first time
} else {
$("#"+page)
.addClass("active")
.animate({ height: "500px" }, 1000,'linear' )
.animate({ width: "500px" }, 400,'linear' )
}
});
HTML
<div id="fold1" class="fold">Div menu item 1</div>
<div id="fold2" class="fold">Div menu item 2</div>
<div id="fold3" class="fold">Div menu item 3</div>
<div id="fold4" class="fold">Div menu item 4</div>
<nav>
<ul>
<li><a href="#" data-page="fold1">Menu item 1</a></li>
<li><a href="#" data-page="fold2">Menu item 2</a></li>
<li><a href="#" data-page="fold3">Menu item 3</a></li>
<li><a href="#" data-page="fold4">Menu item 4</a></li>
</ul>
</nav>
CSS:
.fold {
display: none;
width: 0;
height: 0;
}
.fold.active {
display: inline-block;
}
#fold1 {
border: solid 5px #bada55;
background: red;
}
#fold2 {
border: solid 5px #fed900;
background: aqua;
}
#fold3 {
border: solid 5px #223322;
background: green;
}
#fold4 {
border: solid 5px #55bada;
background: purple;
}
ul {
position: absolute;
top: 50px;
right: 50px;
list-style-type: none;
}