Monday, 19 July 2021

Toggle An Element And Also Remove Its Visibility When Clicking Outside Of The Element - JavaScript

I have a navigation with two items that have submenus. I currently have a class that toggles on and off that shows these submenus when clicked.

I would like it so when I click anywhere on the page they disappear if they are visible.

At the moment I think my code is a bit long-winded for what it currently achieves and perhaps it would be better to use e.target when clicking?

You can currently toggle the menus off-and-on by clicking either menu-item (this includes clicking the visible menu item a second time).

I thought to remove the 'visible' class by clicking outside of the menu-item I could do a simple document.addEventListener('click', function(e) {}) on the entire document to remove the 'visible' class if it was showing, but that doesn't seem to work.

Note: I need to do this without using a blur event listener

Codepen: https://codepen.io/emilychews/pen/bGWVVpq

var menu_item_1 = document.getElementById('item-1'),
    menu_item_2 = document.getElementById('item-2'),
    sub_menu_item_1 = document.getElementById('sub-item-1'),
    sub_menu_item_2 = document.getElementById('sub-item-2')

if (menu_item_1) {
      menu_item_1.addEventListener('click', function(e){
        sub_menu_item_1.classList.toggle('visible')

       // hide submenu 2
        sub_menu_item_2.classList.remove('visible')
    }, false)
}

if (menu_item_2) {
      menu_item_2.addEventListener('click', function(e){
        sub_menu_item_2.classList.toggle('visible')

        // hide submenu 1
        sub_menu_item_1.classList.remove('visible')
    }, false)
}
body {
  display: flex;
  justify-content: center;
  margin: 0;
  height: 100vh;
  width: 100%;
}

header {
  margin-top: 2rem;
  display: flex;
  width: 50%;
  justify-content: space-evenly;
  align-items: center;
  padding: 1rem;
  background: red;
  height: 2rem;
}

.menu-item {
  position: relative;
  padding: 1rem;
  background: yellow;
  cursor: pointer;
}

.submenu {
  display: none; /* changes to 'block' with javascript */
  padding: 1rem;
  background: lightblue;
  position: absolute;
  top: 4rem;
  left: 0;
  width: 6rem;
}

.submenu.visible {
  display:block;
}
<header>
  <div id="item-1" class="menu-item menu-item-1">ITEM 1
    <div id="sub-item-1" class="submenu submenu-1">SUB-ITEM-1</div>
  </div>
  <div id="item-2" class="menu-item menu-item-2">ITEM 2
    <div id="sub-item-2" class="submenu submenu-2">SUB-ITEM-2</div>
  </div>
</header>


from Toggle An Element And Also Remove Its Visibility When Clicking Outside Of The Element - JavaScript

No comments:

Post a Comment