Search⌘ K

Improving Search Functionalities

Explore techniques to enhance search functionality by resetting modals on outside clicks, using Stimulus for global event listening, and implementing debouncing to optimize input handling and server requests.

Adding JavaScript Actions to Search

Our search bar works, but we can still improve it a bit. It would be nice if the modal was reset when we delete all the characters in the search bar, as well as when we click outside the window. However, the latter might be tricky. To get the “outside the window” part to work, by definition, we need to capture click events outside the scope of our Stimulus controller. Luckily, Stimulus has a way to do that.

First, we need to add an action to our search results object:

Ruby
<article class="fixed bg-gray-300 z-10
rounded-3xl ring-4 ring-gray-800
max-w-screen-lg w-full
mr-20 ml-32 px-6 py-2 mt-2
overflow-y-auto overscroll-contain"
data-search-target="results"
data-action="click@window->search#resetOnOutsideClick">

The new line here is data-action="click@window->search#resetOnOutsideClick". Stimulus allows us to attach global event listeners by appending our event name with @window to add listeners for the entire window, or @document for listeners on the global document. In this case, a click anywhere in the window will go to the SearchController’s resetOnOutsideClick method, so we’d better write that (this ...