I trying to use javascript functions to open and close a menu , but it doesn't work

I’m trying to use javascript to open and close a menu, i already can open a blank div, but no matter what i do, i can’t make it close, i’ve tried like 5 diferents codes, and this is the one that worked best. It doesn’t give any type of error(acording to the DevTools), it just don’t remove the div that i created, i tried to use this (operator?) "!!", to check if the div really exists(i thought this was the problem), but again i failed, and now after 3 days of pain to make this work, i gave up and come here to ask if you guys know what’s wrong

const openMenu = document.querySelector('.menu-icon');

//to open
openMenu.addEventListener('click', () =>{
  var closeMenu = document.createElement('div');
  closeMenu.id = "closeMenu1";
  closeMenu.className = "closeMenu";
  closeMenu.style.width = "400px";
  closeMenu.style.height = "600px";
  closeMenu.style.borderRadius = "6px";
  closeMenu.style.position = "relative";
  closeMenu.style.top = "50%";
  closeMenu.style.left = "50%";
  closeMenu.style.backgroundColor = "#99aaa1";
  document.body.appendChild(closeMenu);
},{once: true});

const _closeMenu = document.querySelector('closeMenu1');

//to close

var closingMenu = !!document.querySelector('.closeMenu');

if (closingMenu) {
  console.log("this is", closingMenu);
    _closeMenu.addEventListener('click', () =>{
    _closeMenu.remove();
    });
  }

I also tried without the {once: true}, but it didn’t work, also i’m pretty new to javascript, so yea, this is problably not the best way to do this, but anyways.

>Solution :

You need to add event listener for the closeMenu once it is created while attaching it to the dom. What you are doing is you are accessing that close menu outside the open event listener on page load, The close menu will not be present at that moment on the page.

const openMenu = document.querySelector('.menu-icon');

function closeMyMenu() {
  this.remove();
}

//to open
openMenu.addEventListener('click', () =>{
  const _closeMenu = document.getElementById('closeMenu1');
  if (!_closeMenu) {
    var closeMenu = document.createElement('div');
    closeMenu.id = "closeMenu1";
    closeMenu.className = "closeMenu";
    closeMenu.style.width = "400px";
    closeMenu.style.height = "600px";
    closeMenu.style.borderRadius = "6px";
    closeMenu.style.position = "relative";
    closeMenu.style.top = "50%";
    closeMenu.style.left = "50%";
    closeMenu.style.backgroundColor = "#99aaa1";
    closeMenu.addEventListener('click', closeMyMenu);
    document.body.appendChild(closeMenu);
  } else {
    console.log("Close menu already exists");
  }  
});

Leave a Reply