Improving Search Functionalities
We'll now learn about how to improve search functionalities in the application by adding JavaScript actions.
We'll cover the following...
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:
<article class="fixed bg-gray-300 z-10rounded-3xl ring-4 ring-gray-800max-w-screen-lg w-fullmr-20 ml-32 px-6 py-2 mt-2overflow-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 ...