Search code examples
javascripthtmlcssaddeventlistener

How to remove class on second click addEventListener


I have created a hover dropdown menu that works fine, with the menu as display none and when hovered, it has display:Flex; . The problem is on mobile I want that to happen on click so I have an event listener on click that adds a class to the dropdown menu that makes it visible, but I need to remove that class on the second click.

My code look like this: CSS:

.dropdown-container:hover  .dropdown-menu {
  display: flex;
  animation: openDropDown 0.4s ease 0s 1 forwards;
}}
.dropdown-menuActions { 
  display: flex;
  animation: openDropDown 0.4s ease 0s 1 forwards;
}

HTML

<div class="dropdown-container" id="dropdownContainer">
  <label for="openDropdown" class="dropdown">
    <i class="fa fa-shopping-basket"></i><p class="titleDropdown" >Toate Produsele</p>
    <i class="fas fa-angle-down"></i>
  </label>
  
  <input type="checkbox" id="openDropdown" hidden>

  <div class="dropdown-menu" id="dropdownMenu">
      <span class="btnMobil"><a  href="https://casacarolimarket.ro/categorie/mezeluri-si-carne/">Promotii</a></span> 
...

JS

const test = document.getElementById('dropdownContainer');
let dropdownMenu = document.getElementById('dropdownMenu');

test.addEventListener("click", myFunction);
function myFunction(){
    dropdownMenu.classList.add('dropdown-menuActions');
}

The menu appears fine but I want it to dissapear (Remove the class) on another click anywhere except the dropdown ( including the title " Toate Produsele" ). I do not really want to use jQuery and I do not think it is necessary for removing a class.

I have tried to add another event listener for click but they both trigger in the same time and I need to write something for the second click.


Solution

  • I think you want something like toggle. To show the dropdown you will add a class when user click and close the dropdown by remove the class when user click again.

    You can use classList.contains('dropdown-menuActions') to check the class is exist or not. if existed, then you remove it, otherwise add it.

    Example

    const toggleBtnEle = document.getElementById('toggle-btn');
    
    toggleBtnEle.addEventListener('click', function() {
      const titleEle = document.getElementById('title');
      console.log(titleEle.classList)
      if (titleEle.classList.contains('show')) {
        titleEle.classList.remove('show');
      } else {
        titleEle.classList.add('show');
      }
    });
    #title {
      display: none
    }
    
    .show {
      display: block !important
    }
    <h1 id="title">Show me</h1>
    <button id="toggle-btn">toggle</button>

    Another option will be classList.toggle if you have the state to determine show or not show.

    let visible = false; // <--- change the state to true
    div.classList.toggle("visible", visible);