Having two buttons with same class as
<button class="show-hide-sidebar">Cart</button>
<button class="show-hide-sidebar">Wish</button>
I am trying to show and hide a sidebar but I want to Keep it Open if the sidebar already Opened! this code works fine on each item separately but if I clicked on Cart
btn and want to check Wish
it is closing the sidebar
$(".show-hide-sidebar").on("click", function () {
// Check if the sidebar is already visible (has the 'sidenav-show' class)
if ($("#sidebar").hasClass('sidenav-show')) {
// If sidebar is open, close it
$("#sidebar").removeClass("sidenav-show").addClass("sidenav-hide");
$("#mainbar").removeClass("main-narrow").addClass("main-wide");
} else {
// If sidebar is closed, open it
$("#sidebar").removeClass("sidenav-hide").addClass("sidenav-show");
$("#mainbar").removeClass("main-wide").addClass("main-narrow");
}
});
$(".show-hide-sidebar").on("click", function () {
// Check if the sidebar is already visible (has the 'sidenav-show' class)
if ($("#sidebar").hasClass('sidenav-show')) {
// If sidebar is open, close it
$("#sidebar").removeClass("sidenav-show").addClass("sidenav-hide");
$("#mainbar").removeClass("main-narrow").addClass("main-wide");
} else {
// If sidebar is closed, open it
$("#sidebar").removeClass("sidenav-hide").addClass("sidenav-show");
$("#mainbar").removeClass("main-wide").addClass("main-narrow");
}
});
.box{
height:60px;
width:60px;
margin:20px
}
.sidenav-show{
background:red
}
.sidenav-hide{
background:gold
}
.main-narrow{
background:red
}
.main-wide{
background:gold
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<button class="show-hide-sidebar">Cart</button>
<button class="show-hide-sidebar">Wish</button>
<div class="box sidenav-show" id="sidebar"> </div>
<div class="box main-narrow" id="mainbar"> </div>
2
Answers
How I would do this is add a unique identifier to your buttons. Something like
Then add a variable to track the button clicked
split your click events and pull out the toggle
then your toggle method being the rest
You can use the
toggleClass
jQuery method, and provide the second argument to it (a boolean). We can use a boolean that would be true if you clicked the first button, and false if you clicked the second one. To make this happen, it will be easier if you give your two buttons anid
attribute: