Reputation: 1
I am having an issue to create a Jquery toggle that opens one div
at a time.
I want that only one content shows up when i click on the div
(show
). Here, they both open at the same time.
$(document).ready(function(){
var $content = $(".content").hide();
$(".toggle").on("click", function(e){
$(this).toggleClass("expanded");
$content.slideToggle();
});
});
Also: How can you add the option so that the open div hide once you open a new one but also give you the option to hide the one that is currently open even if you don't open a new div
by clicking on the "hide"
text)
Upvotes: 0
Views: 2884
Reputation: 2233
You could do this several ways. With your current html markup you could use jQuery's Next Function.
$(".toggle").on("click", function(e){
$(this).toggleClass("expanded");
$(this).next().slideToggle();
});
Or you could wrap your toggle and content in a div and use the parent and find functions.
HTML
<div class="wrapper">
<div class="toggle"></div>
<div class="content">Lorem Ipsum </div>
</div>
JavaScript
$(".toggle").on("click", function(e){
$(this).toggleClass("expanded");
$(this).parent().find('.content').slideToggle();
});
If you want all other .content
to slideUp
when you toggle one of them, just select all .content
divs and use jQuery's Not Function to exclude the div you just toggled.
$(".toggle").on("click", function(e){
var target = $(this).parent().find('.content');
$(this).toggleClass("expanded");
target.slideToggle();
$('.content').not( target ).slideUp();
});
Upvotes: 1