Skip to content

Instantly share code, notes, and snippets.

@neisdev
Created April 16, 2023 23:18
Show Gist options
  • Save neisdev/9ae8c683bdb4b2802dba22e1bfe8f023 to your computer and use it in GitHub Desktop.
Save neisdev/9ae8c683bdb4b2802dba22e1bfe8f023 to your computer and use it in GitHub Desktop.
Alpine.js focus() in action
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/tailwind.min.css">
<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.js" defer></script>
</head>
<body class="bg-gray-400">
<div class="container mx-auto px-4 xl:px-64 mt-12 mb-12">
<h2 class="text-2xl font-bold">Modal</h2>
<div x-data="{ isOpen: false }">
<button
class="bg-blue-700 text-white px-4 py-3 mt-4 text-sm rounded"
@click="isOpen = true
$nextTick(() => $refs.modalCloseButton.focus())
"
>
Open Modal
</button>
<div
style="background-color: rgba(0, 0, 0, .5)"
class="mx-auto absolute top-0 left-0 w-full h-full flex items-center shadow-lg overflow-y-auto"
x-show="isOpen"
>
<div class="container mx-auto rounded p-4 mt-2 overflow-y-auto">
<div class="bg-white rounded px-8 py-8">
<h1 class="font-bold text-2xl mb-3">Modal Title</h1>
<div class="modal-body">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro amet repellat recusandae.</p>
</div>
<div class="mt-4">
<button
class="bg-blue-700 text-white px-4 py-3 mt-4 text-sm rounded"
@click="isOpen = false"
x-ref="modalCloseButton"
>
Close Modal
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<!-- Further reading: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_html_blur -->
<!-- Credit: https://scrimba.com/g/galpinejs -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment