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
You forgot to remove
hide
property when showing the button andshow
property when hiding it. The way your code is set up the button’sclassList
looks like that[] -> [hide] -> [hide, show] …
but should look like
[] -> [hide] -> [show] …
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)
If your class only have
display: none
in it, I suggest you to usemyBtn.style.display = 'none'