How can I auto-focus on an item-gallery search bar?

Customizing the Website Integration with Javascript

Adam Specker avatar
Written by Adam Specker
Updated over a week ago

You can have a site visitor's cursor automatically focus on the search bar by adding the following Javascript snippet to your site.


The best place to add this code will depend on your site platform, setup, and needs.

We recommend adding it as Code Injection in your site footer or placing it at the end of the body. If your site builder has an area where you can place custom Javascript to be executed, that is also a good option (no <script> tag needed in this case).

<script>
var focus = function(isRetryAttempt = false) {
// time is in milliseconds
var timeBeforeRetry = 500;
var el = document.getElementById("gspro-search-input")
if (el) {
el.focus();
return;
}
if (isRetryAttempt) return;
setTimeout(function() { focus(true) }, timeBeforeRetry);
};
window.onload = function() {
focus();
}
</script>

NOTE: This script relies on certain resources being loaded to work properly. It will retry once in case those resources have not been loaded yet. The optimal time to wait between retries will vary depending on what other resources your site is loading. This value can be easily changed by editing the value of timeBeforeRetry, which is set at 500 milliseconds above.

If you are noticing the search bar is not being foused, increase the value of timeBeforeRetry.

Did this answer your question?