How to hide a div by clicking the same toggle button or elsewhere in the document
Right now I can show a div by clicking a button, and hide it using the same button. That's working fine, but I would also like a user to 开发者_运维知识库be able to click outside of the newly shown div or the button to show it, and still hide it.
Hey guys, this is my first time asking a question here, so I'm sorry if I didn't enter the code right or something. Basically I have a button, and I want only one way to open a hidden div (clicking said button), but two ways to close it (clicking the same opening button or elsewhere in the document).
Here is my current code.
//This part works fine for opening and closing, but you can't click outside the button to make it close once opened.<br/>
$(".account").click(function () {
$(".accountlinks").toggle();
$(".account").toggleClass("active");
});
$(document).click(function(e) {
$('.accountlinks').hide();
$(".account").removeClass("active");
});
$('.accountlinks').click(function(e) {
e.stopPropagation();
});
Is there some way to see if it is already opened, and then close it with the document.click function using this $('.account').hasClass('active');
in some way?
Thank you for your help.
Here's my approach: Rather than giving the "active" class to the button, as you appear to be doing, I give it to the div. That way, you can select open divs in the document click using the "active" class. Check it out:
$(function() {
$("#toggler").click(function(e) {
$("#toggled").toggle().toggleClass("active");
e.stopPropagation();
});
$(document).click(function(e) {
$('.active').hide().removeClass('active');
});
$("#toggled").click(function(e) {
e.stopPropagation();
});
});
And here's a demo of that: http://jsfiddle.net/Ender/xNQN3/
精彩评论