Delete class after clicking outside div

I know this is an old question, but I searched a lot. I want to delete a class after clicking outside the 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! thanks

+5
source share
1 answer

This is due to the spread of the event.

When the user-login-top button is clicked, the first click on the handle fires, which adds a class, then, due to the propagation of events, the handler attached to the document fires when it satisfies if the condition 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> 
+14
source

Source: https://habr.com/ru/post/1205942/


All Articles