Reputation: 29
I have a div which open when I click on the question mark icon (upper right of the document). When clicked I add a class which transform the question mark icon in close icon. When I click outside the div, the div closed and the class is removed, closed icon becomes the question mark icon. But now when I click in the document, it add and removed the class whenever the div is open or closed.
If anybody have an idea how I can removed the class when cliked on the document only when the div is open. Thanks
jQuery('.showmenu').click(function(e){
e.stopPropagation();
jQuery('.about-btn').toggleClass( "active");
jQuery('.about').slideToggle('fast');
});
jQuery('.about').click(function(e){
e.stopPropagation();
});
jQuery(document).click(function(){
jQuery('.about-btn').toggleClass( "active");
jQuery('.about').slideUp('fast');
});
Upvotes: 0
Views: 964
Reputation: 54
IMO
add/bind $(document).click
only when/on $('.showmenu').click
function.
Later do $(document).unbind('click')
in $(document).click
function
ex:
$('.showmenu').click(function (e) {
e.stopPropagation();
$('.about-btn').toggleClass("active");
$('.about').slideToggle('fast');
//Binding click function on document
$(document).click(function () {
$('.about-btn').toggleClass("active");
$('.about').slideUp('fast');
$(document).unbind('click'); //Unbind click
});
});
$('.about').click(function (e) {
e.stopPropagation();
});
Upvotes: 1
Reputation: 6511
Instead of registering the click event to document
, you could have an overlay under the popup div that appears together and have the close event register on that instead.
Or you could also store the state in a variable like so:
var isOpen = false;
jQuery('.showmenu').click(function(e){
e.stopPropagation();
jQuery('.about-btn').toggleClass( "active");
jQuery('.about').slideToggle('fast');
isOpen = true;
});
jQuery('.about').click(function(e){
e.stopPropagation();
});
jQuery(document).click(function(){
if(!isOpen) return; // early return if not opened
jQuery('.about-btn').toggleClass( "active");
jQuery('.about').slideUp('fast');
});
Upvotes: 0
Reputation: 10166
Only remove the class active
instead of toggling it:
jQuery(document).click(function(){
jQuery('.about-btn').removeClass( "active");
jQuery('.about').slideUp('fast');
});
If i understood correctly, you never need to set the class active
when clicking outside the div, so it should do the trick
Upvotes: 0