Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda