skip to Main Content

In my code, the rectangle should hide when I click on it and appear when I press Esc. Everything works only once. Why? And how can I solve this problem? Thank you for your attention.

const myBtn = document.querySelector('[data-btn]')


myBtn.addEventListener('click', (e) => {
   if (e.target === myBtn) {
      myBtn.classList.add('hide')

   }
})


document.addEventListener('keydown', (e) => {
   if (e.code === "Escape") {
      myBtn.classList.add('show')
   }
})

2

Answers


  1. You forgot to remove hide property when showing the button and show property when hiding it. The way your code is set up the button’s classList looks like that

    [] -> [hide] -> [hide, show] …

    but should look like

    [] -> [hide] -> [show] …

    Login or Signup to reply.
  2. According to your code, when the button is clicked, it will add show class and esc will add hide class

    But if you click then press esc, the button will have two classes: hide and show.

    So this is a fix to your code: (sorry I coded this in my phone)

    const myBtn = document.querySelector('[data-btn]')
    
    
    myBtn.addEventListener('click', (e) => {
       if (e.target === myBtn) {
          myBtn.classList.add('hide')
          myBtn.classList.remove('show')
       }
    })
    
    
    document.addEventListener('keydown', (e) => {
       if (e.code === "Escape") {
          myBtn.classList.add('show')
          myBtn.classList.remove('hide')
       }
    })
    

    If your class only have display: none in it, I suggest you to use myBtn.style.display = 'none'

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search