Search code examples
javascriptbuttoneventsclickescaping

Why my javascript code work, but only once?


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')
   }
})

Solution

  • 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'