Solution 1 :

You can do this by creating two classes .

  1. will contain all the styles when button is active(i.e clicked)

  2. 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");
    }
  })

Solution 2 :

you can use element.classList.toggle("ClassName"); to add/remove class on click

  1. select the toggle-able element
  2. select the element to attach the click listener
  3. add click event listener
    var element = document.querySelector(".myclass");
    var someElement = document.querySelector(".otherClass");
    someElement.addEventListener('click', function () {
        element.classList.toggle("show");
    });

Problem :

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 !

Comments

Comment posted by Emiel Zuurbier

I’ve tried a few methods that didn’t work

Comment posted by Nathaniel Flick

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.

By