Issue
I am using this code to control the display of a sidebar via add/remove class.
The first 2 functions work, however I have also added a 3rd function to try to remove class active when clicking outside of the sidebar.
Now nothing works, it just pushes some body content aside.
jQuery(document).ready(function($){
$(".btn-open-sidecart").click(function(){
$('.sidebar').addClass("active");
$('.overlay').addClass("active");
});
$(".btn-close-sidecart").click(function(){
$('.sidebar').removeClass("active");
$('.overlay').removeClass("active");
});
$('body').click(function(event){
if($(event.target).attr('class') !== "sidebar" && $(event.target).attr('class') !== "btn-close-sidecart") {
$('.sidebar').removeClass('active');
$('.overlay').removeClass('active');
};
});
});
How can I fix this to also removeClass('active')
when clicking outside the sidebar?
Solution
You are only checking if the element you are clicking on is ".sidebar" or ".btn-close-sidecart" but not if one of their parents has these class.
So even clicking on a button inside ".sidebar" will trigger your method as they are note ".sidebar"
Here is a working example
$(".btn-open-sidecart").click(function(){
$('.sidebar').addClass("active");
$('.overlay').addClass("active");
});
$(".btn-close-sidecart").click(function(){
$('.sidebar').removeClass("active");
$('.overlay').removeClass("active");
});
$('body').click(function(event){
const ignoreElements = ["btn-open-sidecart", "sidebar"];
let pass = true;
$(ignoreElements).each(function(key, value) {
if ($(event.target).hasClass(value) || $(event.target).closest(`.${value}`).length > 0) {
pass = false;
}
});
if (pass) {
$('.sidebar').removeClass('active');
$('.overlay').removeClass('active');
}
});
* {
padding: 0;
margin: 0;
}
.sidebar {
position: fixed;
z-index: 3;
width: 200px;
height: 100%;
background: darkgrey
}
.sidebar:not(.active) {
display: none;
}
.btn-close-sidecart {
position: absolute;
width: 20px;
height: 20px;
top 5px;
right: 5px;
background: grey;
cursor: pointer;
text-align: center;
}
.overlay {
position: fixed;
z-index: 2;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5)
}
.overlay:not(.active) {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="sidebar">
<div class="btn-close-sidecart">
x
</div>
<ul>
<li>
<button onclick="console.log('test')">button 1</button>
</li>
<li>
<button onclick="console.log('test2')">button 2</button>
</li>
</ul>
</div>
<div class="overlay">
</div>
<div class="content">
<button class="btn-open-sidecart">Open sidebar</button>
</div>
</div>
Answered By - Christian
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.