Problem
While creating a page for a client at work, I encountered an issue with a slide-out search bar. When clicking the button to open the search input field (which starts off hidden), I want the focus to shift to that input field.
Oddly, I found that the only way to achieve this is by placing the focus code in a setTimeout function with a minimum delay of about 50ms. Setting it to 0ms does not work.
Interestingly, when I close the search bar by clicking the open/close button, I briefly notice that the input field receives the focus/cursor. However, this does not happen when the search bar opens as intended, unless the setTimeout workaround is used...
Attempts so far
I have tried setting the focus to another element first and then blurring it before focusing on the desired input field. [x]
Attempted wrapping the
.focus()
method inside asetTimeout
with a time of 0 ms. [x]Successfully set the focus to a different 'test' input field that I created. [WORKS]
- Added a
tabindex
of -1 to the input field. [x]
const icon = document.getElementById("search-icon");
const form = document.getElementById("search-form");
const input = document.getElementById("search-input");
icon.parentElement.addEventListener("click", e => {
form.classList.toggle("visible");
icon.classList.toggle("fa-search");
icon.classList.toggle("fa-times");
setTimeout(() => input.focus(), 50);
});
<div class="header__search">
<i id="search-icon" class="fas fa-search">click me</i>
<form
id="search-form"
class="header__search-area"
onclick="event.stopPropagation()"
>
<input
id="search-input"
tabindex="-1"
type="text"
placeholder="Enter Search Term..."
/>
<button type="submit">search</button>
</form>
</div>
To give you a clear picture, clicking the icon (id=search-icon) reveals the absolute positioned form next to it, which contains the 'input' field I'm trying to focus on.
If anyone can shed some light on this peculiar behavior, I would greatly appreciate it. So far, my searches on Google have been fruitless.