Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!