Reputation: 9
I have created a menu where by clicking a category a div pops up, but I also want other category divs to close when pressing a new one. I'm quite new to Jquery, and even though the first script was easy to write, I'm not sure how to continue. I tried using answers I found here that worked perfectly in the linked jsfiddle, but none of them worked when I tried to use them in my page. Here is an example: http://jsbin.com/eCAwiVA/1 Keep in mind I'm trying to do this on a tumblr page.
I have spent hours trying to understand now, I'd be so happy if someone could explain - thank you so much in advance!
Upvotes: 0
Views: 456
Reputation: 938
Here is a quick JS Bin with the answer to your question: http://jsbin.com/eCAwiVA/15/
Note: If you can, you should only use one $(document).ready()
function and register all events like I did it.
To the solution: Like you can see, I just use jQuery's .is()
-method to check if the other <div>
is visible or not. If it is visible, I just hide it, otherwise I just toggle the <div>
which is supposed to be opened anyway.
Code:
$(document).ready(function(){
$("#cabout").click(function () {
if ($("#popsocial").is(":visible")) {
$("#popsocial").hide();
}
$("#popabout").toggle();
});
$("#csocial").click(function () {
if ($("#popabout").is(":visible")) {
$("#popabout").hide();
}
$("#popsocial").toggle();
});
});
Upvotes: 1
Reputation: 2169
If you want to keep this HTML construction, which as previous posts suggested I would advise against, you could check if the siblings of the toggled element are vissible or not. If they are visible you can toggle them as well.
$(document).ready(function(){
$("#cabout").click(function () {
$("#popabout").toggle();
if ($("#popabout").siblings().css('display') != 'none'){
$("#popabout").siblings().toggle();
}
});
$("#csocial").click(function () {
$("#popsocial").toggle();
if ($("#popsocial").siblings().css('display') != 'none'){
$("#popsocial").siblings().toggle();
}
});
});
Upvotes: 0