Remove jQuery usage from shipped templates
Let's remove jQuery from the autocomplete.php and instantsearch.php templates in favor of vanilla javascript.
Got this started in https://github.com/WebDevStudios/wp-search-with-algolia/tree/feature/231-remove-jquery-in-templates
Needs some review/confirmation on the changing of this:
jQuery( '#algolia-search-box input' ).attr( 'type', 'search' ).trigger( 'select' );
to something else.
As is, I have:
document.querySelector("#algolia-search-box input[type='search']").dispatchEvent(new Event('select'));
but I don't believe I'm matching things up properly yet.
@tw2113 It turns out we have select method for selecting text in vanilla JavaScript as well 😄
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
So your code will change to:
document.querySelector( "#algolia-search-box input[type='search']" ).select();
I have almost all of autocomplete.php converted except for https://github.com/WebDevStudios/wp-search-with-algolia/blob/feature/231-remove-jquery-in-templates/templates/autocomplete.php#L192-L196
I tried addEventListener but it threw errors so I'm not doing some part correct.
I also interestingly needed to update the input_selector at https://github.com/WebDevStudios/wp-search-with-algolia/blob/feature/231-remove-jquery-in-templates/includes/class-algolia-template-loader.php#L84-L86 to make it find the inputs. Specifically the ' in the not was apparently not valid.
We're close!
I'm wondering if this lingering spot is maybe ok, based on https://github.com/WebDevStudios/wp-search-with-algolia/blob/main/js/autocomplete.js/dist/autocomplete.js#L1283-L1315
I don't believe the $ is a jQuery object in this case, and I think they rolled their own .on
@tw2113 Looks good to me. They have defined their own on function to detect events in the autocomplete UI.
With that handled, I believe we have everything converted to working vanilla JS, but we should probably make sure to have it well tested, as well as where possible, notify existing users that we're making these changes.
We could add a new sticky thread at the top of https://wordpress.org/support/plugin/wp-search-with-algolia/ as needed.
Looking at our stats, 83% of our users are on version 2.1 or higher, 17%-ish on 1.8 or earlier. No version 1.9 released, and 2.0 may be in "other"
https://wordpress.org/plugins/wp-search-with-algolia/advanced/
Closing as done as this was merged in with #247