Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  53] [ 3]  / answers: 1 / hits: 53221  / 10 Years ago, fri, october 31, 2014, 12:00:00

I know this is a old question , but i've searched a lot .
i want to remove class after clicked outside the like body . here is my code :

Html



   <div id=user-login-top>Enter</div>
<div id=user-login-wrapper class=>visible</div>


Jquery



$(function () {
$(#user-login-top).on(click, function () {
$(#user-login-wrapper).addClass(wide);
});
$(document).on(click, function (e) {
if ($(e.target).is(#user-login-wrapper) === false) {
$(#user-login-wrapper).removeClass(wide);
}
});
});


and here is the fiddle : Fiddle



Appreciate your help !?

Thx


More From » jquery

 Answers
16

It is because of the propagation of event.



When you click on user-login-top, the first click handle is triggered which is adding the class, then because of event propagation the handler attached to the document is triggered where it satisfies the if condition and removes the class.



One possible solution here is to use event.stopPropagation()





$(function() {
$(#user-login-top).on(click, function(e) {
$(#user-login-wrapper).addClass(wide);
e.stopPropagation()
});
$(document).on(click, function(e) {
if ($(e.target).is(#user-login-wrapper) === false) {
$(#user-login-wrapper).removeClass(wide);
}
});
});

#user-login-wrapper {
opacity: 0;
}
#user-login-wrapper.wide {
opacity: 1 !important;
}

<div id=user-login-top>ورود</div>
<div id=user-login-wrapper class=>visible</div>








Another is





$(function() {
$(#user-login-top).on(click, function(e) {
$(#user-login-wrapper).toggleClass(wide);
});
$(document).on(click, function(e) {
if ($(e.target).is(#user-login-wrapper, #user-login-top) === false) {
$(#user-login-wrapper).removeClass(wide);
}
});
});

#user-login-wrapper {
opacity: 0;
}
#user-login-wrapper.wide {
opacity: 1 !important;
}

<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script>
<div id=user-login-top>ورود</div>
<div id=user-login-wrapper class=>visible</div>




[#68952] Wednesday, October 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annalieset

Total Points: 733
Total Questions: 92
Total Answers: 109

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
;