Building a Dropdown with Tippy #3232
Replies: 2 comments 1 reply
-
Pass it into the function, it's easier <div x-data>
<button @click="$dropdown($refs.dropdown)" type="button">
Menu
</button>
<ul class="dropdown" x-ref="dropdown">
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
</ul>
</div>
<script>
document.addEventListener('alpine:init', () => {
// Magic: $tooltip
window.Alpine.magic('dropdown', el => dropdown => {
let instance = tippy(el, {
content: dropdown,
trigger: 'manual',
placement: 'bottom',
interactive: true,
allowHTML: true,
})
instance.show()
})
})
</script> |
Beta Was this translation helpful? Give feedback.
-
While Tippy.js is excellent for tooltips and popovers, I've found that for standard dropdown menus, Alpine.js's built-in directives provide everything needed with less overhead. Here's a pattern I've used successfully across multiple projects: <div x-data="{ open: false }">
<button
@click="open = !open"
@keydown.escape.window="open = false">
Menu
<svg :class="{'rotate-180': open}"><!-- Icon --></svg>
</button>
<div
x-show="open"
x-transition:enter="transition ease-out duration-100"
x-transition:enter-start="opacity-0 transform scale-95"
x-transition:enter-end="opacity-100 transform scale-100"
@click.away="open = false">
<!-- Dropdown content -->
</div>
</div> This approach gives you:
All without additional dependencies beyond Alpine itself. I've documented the complete implementation with positioning techniques here: That said, if you need advanced positioning like edge detection or viewport containment, Tippy definitely adds value. It really depends on your specific requirements. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi all. Currently learning Alpine JS.
First question is can you access magics within Alpine.directive or Alpine.magic?
The end goal is I want to pass in an element/node as a target for the dropdown, whilst leveraging Tippy for positioning.
Using the example on the components section:
Rather than base this off of the tooltip example component, should I be working tippy into the dropdown component example somehow?
Beta Was this translation helpful? Give feedback.
All reactions