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

164
Visualizações
Prevent multiple EventListeners from clashing on focus with Vanilla JavaScript

I'm extending my existing navigation for accessibility, but having issues when hitting "Enter" on the keyboard whilst the target are focused. The eventlisteners for the search and/or navigation toggle fire when any other element is focused on, this could be any anchor or any focused element.

Mouse clicking the individual elements (and clicking out of form) functions the way it needs to. However, on focus THEN hitting "Enter" anywhere on the page, it fires off, if not the right one, both events. Any help would be appreciated.

/* Search */

let searchToggle = document.querySelector('.search-toggle'),
  searchForm = document.querySelector('.search-form');

function searchClick(event) {
  event.stopPropagation();
  let toggled = searchToggle.contains(event.target);
  if (toggled) {
    searchForm.classList.add('show-search-form');
  } else if (!event.target.closest('.show-search-form')) {
    searchForm.classList.remove('show-search-form');
  }
}

function searchFocus(event) {
  if (event.keyCode === 13) {
    event.stopPropagation();
    searchToggle.click();
  }
}

document.addEventListener('click', searchClick, false);
document.addEventListener('keyup', searchFocus, false);

/* Navigation */

let navToggle = document.querySelector('.toggle'),
  nav = document.querySelector('.nav');

navToggle.addEventListener('click', () => {
  nav.classList.toggle('toggle-menu');
});

function navFocus(event) {
  if (event.keyCode === 13) {
    event.stopPropagation();
    navToggle.click();
  }
}

document.addEventListener('keyup', navFocus, false);
*:focus-visible {
  outline: 5px solid #333333;
}

.search-form,
.nav {
  display: none;
}

.search-form.show-search-form {
  display: block;
}

.nav.toggle-menu {
  display: block;
}
<div class="search-toggle" tabindex="0">
  <span>Toggle Search</span>
</div>
<div class="search-form">
  <span>Test Form</span>
</div>

<div class="toggle" tabindex="0">
  <span>Toggle Menu</span>
</div>

<nav class="nav">
  <ul>
    <li><a href="#">Test</a></li>
    <li><a href="#">Test</a></li>
    <li><a href="#">Test</a></li>
  </ul>
</nav>

about 4 years ago · Juan Pablo Isaza
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