Why Doesn't My Script Emulate a Click on the Search Icon Properly?

Hi,

I’m trying to programmatically open and focus the search bar on my Shopify site (Dawn Theme). Here’s the code I’ve used:

var searchToggle = document.querySelector('.header__icon--search');
if (searchToggle) {
    searchToggle.click();
}

This successfully opens the search bar but doesn’t focus on the input field like it does when I manually click the search icon.

Does anyone know why this script doesn’t fully emulate a click on the search icon and how I can fix it so the search input is focused automatically?

Thanks in advance for your help!

Varies wildly among themes, it’s probably that the themes javascript that creates a new focus is wired to a parent element or subelement.

Or listens for a mousdown/mouseup event.

Generally you need to also handle the focus change when doing indirect click() tactics like this to achieve a behavior.

When search bar is open by user interaction, the window already has focus somewhere (since visitor has clicked the search icon) and theme JS moves focus to the input field.

When you do .click() from JS, the window may have no focus and in this case the cursor would not be shown.