We don’t support multiple instances of Autocomplete in the same page, as only one of them can attach mouse/pointer events to the document.
As an alternative to having 2 instances of Autocomplete, you can retrieve the viewport size when the document is loaded and conditionally instantiate either the mobile or the desktop version.
If there’s a need to dynamically change the target, you can rely on window.matchMedia()
and destroy/recreate Autocomplete in its change
event.
If you need 2 instances at the same time, you can explicitly tell all the Autocomplete instances to close when a click happens outside of them, like this:
const autocomplete1 = autocomplete({ /* ... */ });
const autocomplete2 = autocomplete({ /* ... */ });
document.addEventListener('click', (event) => {
const clickInsideAutocomplete = event.target.closest('.aa-Autocomplete');
if (!clickInsideAutocomplete) {
autocomplete1.setIsOpen(false);
autocomplete2.setIsOpen(false);
}
});
Note that this won’t work in some cases, for example with Shadow DOM, in IE11, etc. You might need to adapt this snippet to your specific requirements.
How to do this with the Algolia Shopify Extension
If you are using our Shopify Extension, you can access the autocomplete with the window object
window.algoliaShopify.externals.autocomplete
Here are the steps you can follow for this:
Turn on the global “Agolia Search App Block”
turn off the autocomplete settings in the Algolia Shopify integration.
Then you can fetch the autocomplete from the window.algoliaShopify.config object