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 >
<div >
<button id="button-burger" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span ></span>
</button>
<div id="navbarNav">
<ul >
.........
.........
.........
.........
</nav>
<div 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 !
CodePudding user response:
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");
});
CodePudding user response:
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");
}
})