Skip to content

Instantly share code, notes, and snippets.

@Howard3
Created May 11, 2023 15:09
Show Gist options
  • Save Howard3/0ea0d27c67025f8fc7958671902a38e3 to your computer and use it in GitHub Desktop.
Save Howard3/0ea0d27c67025f8fc7958671902a38e3 to your computer and use it in GitHub Desktop.
HTMX/AlpineJS TypeAhead.
{{define "content"}}
<div id="results">
{{if or .Notice .Error}}
{{if .Error}}
<div
class="alert flex rounded-lg border border-error px-4 py-4 text-error sm:px-5"
>
{{.Error}}
</div>
{{else}}
<p class="block p-2 text-sm">{{.Notice}}</p>
{{end}}
{{else}}
{{if not .Users}}
<p class="block p-2">No results found</p>
{{end}}
{{range .Users}}
<a
href="#"
x-on:click.prevent="showResults = false;
$refs.searchInput.value = $event.target.getAttribute('data-value')"
data-value="{{.Email}}"
class="block p-2 hover:bg-gray-200">{{.Display}}</a>
{{end}}
{{end}}
</div>
{{end}}
{{define "user_search"}}
<div x-ref="user" x-data="{ showResults: false }" class="relative" hx-push-url="false">
<input
x-on:input.debounce.300="showResults = true"
x-on:blur="setTimeout(() => showResults = false, 200)"
type="text" class="w-full p-2 border border-gray-300 rounded"
placeholder="Search for a user"
autocomplete="off"
name="q"
x-ref="searchInput"
hx-get="/users/typeahead"
hx-trigger="input"
hx-indicator="#loading"
hx-target="#results"
hx-swap="outerHTML">
<div id="loading" class="hidden">
<div class="p-2">
<div class="w-4 h-4 border-t-2 border-blue-500 animate-spin mx-auto"></div>
</div>
</div>
<div x-show="showResults" class="absolute w-full mt-1 border border-gray-300 bg-white text-gray-700 rounded shadow-lg">
<div id="results">
<!-- Results will be populated here -->
</div>
</div>
</div>
{{end}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment