Answer the question
In order to leave comments, you need to log in
How to hide a div when clicking outside the div?
1) How to remove the .userbar_show class if clicked outside the block itself?
2) Is it correct to write a separate function for the button that closes this div?
$('.js-userbar-toggler').click( function(event) {
$("body").toggleClass("body__scroll-hidden"); /* на боди вешается стиль который запрещает скролл */
$(".userbar").toggleClass("userbar_show"); /* выезжает сайдбар блок */
});
$('.js-userbar-close').click( function(event) {
$("body").removeClass("body__scroll-hidden");
$(".userbar").removeClass("userbar_show");
});
Answer the question
In order to leave comments, you need to log in
If you need to hide a pop-up window by clicking on the background, then you usually hang a click handler on the background element.
$(".userbar").removeClass("userbar_show") - will work regardless of where this code is called and on all elements with class "userbar". And I consider the use of functions and binding them through onclick in the html code to be a more correct approach.
That is, the code will be like this:
function userbar_show(){
$("body").toggleClass("body__scroll-hidden"); /* на боди вешается стиль который запрещает скролл */
$(".userbar").toggleClass("userbar_show");
}
function userbar_hide(){
$("body").removeClass("body__scroll-hidden");
$(".userbar").removeClass("userbar_show");
}
<div class="wrapper">
<div class="hower_backgroud" onclick="userbar_hide();"></div>
<div class="userbar" onclick="userbar_hide();">
<div class="js-userbar-toggler" onclick="userbar_show();"></div>
<div class="js-userbar-close" onclick="userbar_hide();"></div>
</div>
</div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question