Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

265
Visualizações
document.addEventListener in function not working

I'm trying to hide the "modal" box when the user press Esc key.
  • So, I first check where the box contains class - 'hidden', which technically hide the box in UI.
  • Then if it's not hidden (the box does not contain class - 'hidden') and appearing on screen, the function will wait for the Esc key for the box to be disappeared.

Showing and hiding the box parts working just fine, but document.addEventListener part is not working.

const btnopenModal = document.querySelectorAll('.show-modal');
const btnCloseModal = document.querySelector('.close');
const overlay = document.querySelector('.overlay');
const modal =document.querySelector('.modal');

const showModal = function() {
    modal.classList.remove('hidden');
    overlay.classList.remove('hidden');
};

const hideModal = function() {
    modal.classList.add('hidden');
    overlay.classList.add('hidden');
}

for(let i = 0; i < btnopenModal.length; i++) 
    btnopenModal[i].addEventListener('click', showModal);

btnCloseModal.addEventListener('click', hideModal);
overlay.addEventListener('click', hideModal);

if(!overlay.classList.contains('hidden')) {
    document.addEventListener('keypress', function(e) {
        console.log(e.key);
        if(e.key === 'Escape') {
            hideModal();
        }
    })
};

Any other way around for this to work?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Move if condition into callback. You want to always add keypress listener, just do not execute hideModal() if !overlay.classList.contains('hidden')

const btnopenModal = document.querySelectorAll('.show-modal');
const btnCloseModal = document.querySelector('.close');
const overlay = document.querySelector('.overlay');
const modal =document.querySelector('.modal');

const showModal = function() {
    modal.classList.remove('hidden');
    overlay.classList.remove('hidden');
};

const hideModal = function() {
    modal.classList.add('hidden');
    overlay.classList.add('hidden');
}

for(let i = 0; i < btnopenModal.length; i++) 
    btnopenModal[i].addEventListener('click', showModal);

btnCloseModal.addEventListener('click', hideModal);
overlay.addEventListener('click', hideModal);

document.addEventListener('keypress', function(e) {
   console.log(e.key);
   if(e.key === 'Escape' && !overlay.classList.contains('hidden')) {
      hideModal();
   }
});
about 4 years ago · Juan Pablo Isaza Relatório

0

I would think that your if statement is evaluated when the webpage first runs, and my guess is that the if statement evaluates to false as it probably does contain the class "hidden" at first. I don't understand why you put it the key handler inside of an if statement, if it is for safety you should put it inside your function like so:

document.addEventListener('keypress', function(e) {
    if(!overlay.classList.contains('hidden')) {
      console.log(e.key);
      if(e.key === 'Escape') {
          hideModal();
      }
    };
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda