You can do this by creating two classes .
-
will contain all the styles when button is active(i.e clicked)
-
will contain all the styles when button is inactive .
css
.active{...styles when button is clicked}
.inactive{ ... }
JS
const button = document.getElementById(' id for that button');
button.addEventListener("click",()=>{
if(button. classList.contains(".active")){
button. classList.remove(".active");
button.classList.add(".inactive")
}else{
button.classList.add(".active");
button.classList.remove(".inactive");
}
})
you can use element.classList.toggle("ClassName");
to add/remove class on click
- select the toggle-able element
- select the element to attach the click listener
- add click event listener
var element = document.querySelector(".myclass");
var someElement = document.querySelector(".otherClass");
someElement.addEventListener('click', function () {
element.classList.toggle("show");
});
I am building a simple website with bootstrap5 (no JS for now).
When I minimize the screen to have the nav bar become a burger button, I want that whenever I click on it and the menu shows up, the margin-top of the element below to augment so that the menu isn’t written on top of it.
I think there is a way to do that in JS but I’ve tried a few methods that didn’t work.
Here an excerpt of my code:
<nav class="navbar navbar2 navbar-expand-lg navbar-light bg-white">
<div class="container-fluid">
<button class="navbar-toggler" id="button-burger" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav navbar-center2">
.........
.........
.........
.........
</nav>
<div class="container-fluid nav-wrapper" id="container-below-header">
Basically I want to change the class of the div below to change whenever I click on the button.
Thanks for your help !
Agreed we need to see the JS you have tried. Basically you need a click event that toggles a class on the element you want to show/hide.