Popover on hover vue headllessui - javascript

I'm trying to implement the popover from headlessui of vue package with hover. I try to use the mouseenter and mouseleave and the other mouse events but nothing change.
Any solution? There is a better solution? i search on internet I cant nothing about this. I search on headlessui github discussions but nothing.
<template>
<div class="fixed top-16 w-full max-w-sm px-4">
<Popover v-slot="{ open }" class="relative">
<PopoverButton
:class="open ? '' : 'text-opacity-90'"
class="group inline-flex items-center rounded-md bg-orange-700 px-3 py-2 text-base font-medium text-white hover:text-opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75"
>
<span>Solutions</span>
<ChevronDownIcon
:class="open ? '' : 'text-opacity-70'"
class="ml-2 h-5 w-5 text-orange-300 transition duration-150 ease-in-out group-hover:text-opacity-80"
aria-hidden="true"
/>
</PopoverButton>
<transition
enter-active-class="transition duration-200 ease-out"
enter-from-class="translate-y-1 opacity-0"
enter-to-class="translate-y-0 opacity-100"
leave-active-class="transition duration-150 ease-in"
leave-from-class="translate-y-0 opacity-100"
leave-to-class="translate-y-1 opacity-0"
>
<PopoverPanel
class="absolute left-1/2 z-10 mt-3 w-screen max-w-sm -translate-x-1/2 transform px-4 sm:px-0 lg:max-w-3xl"
>
<div
class="overflow-hidden rounded-lg shadow-lg ring-1 ring-black ring-opacity-5"
>
<div class="relative grid gap-8 bg-white p-7 lg:grid-cols-2">
<a
v-for="item in solutions"
:key="item.name"
:href="item.href"
class="-m-3 flex items-center rounded-lg p-2 transition duration-150 ease-in-out hover:bg-gray-50 focus:outline-none focus-visible:ring focus-visible:ring-orange-500 focus-visible:ring-opacity-50"
>
<div
class="flex h-10 w-10 shrink-0 items-center justify-center text-white sm:h-12 sm:w-12"
>
<div v-html="item.icon"></div>
</div>
<div class="ml-4">
<p class="text-sm font-medium text-gray-900">
{{ item.name }}
</p>
<p class="text-sm text-gray-500">
{{ item.description }}
</p>
</div>
</a>
</div>
<div class="bg-gray-50 p-4">
<a
href="##"
class="flow-root rounded-md px-2 py-2 transition duration-150 ease-in-out hover:bg-gray-100 focus:outline-none focus-visible:ring focus-visible:ring-orange-500 focus-visible:ring-opacity-50"
>
<span class="flex items-center">
<span class="text-sm font-medium text-gray-900">
Documentation
</span>
</span>
<span class="block text-sm text-gray-500">
Start integrating products and tools
</span>
</a>
</div>
</div>
</PopoverPanel>
</transition>
</Popover>
</div>
</template>

Seems like common request in HeadlessUI community.
Another solution found this solution on Github that worked fine for me.
for vanilla vue 3 with js the original solution link Github Issue
Nuxt 3 with typescript maintaining accessibility here's the code ↓
<script setup lang="ts">
import { Popover, PopoverButton, PopoverPanel } from '#headlessui/vue'
interface Props {
label: string
hasHref?: boolean
href?: string
}
const props = defineProps<Props>()
const popoverHover = ref(false)
const popoverTimeout = ref()
const hoverPopover = (e: any, open: boolean): void => {
popoverHover.value = true
if (!open) {
e.target.parentNode.click()
}
}
const closePopover = (close: any): void => {
popoverHover.value = false
if (popoverTimeout.value) clearTimeout(popoverTimeout.value)
popoverTimeout.value = setTimeout(() => {
if (!popoverHover.value) {
close()
}
}, 100)
}
</script>
<template>
<Popover v-slot="{ open, close }" class="relative">
<PopoverButton
:class="[
open ? 'text-primary' : 'text-gray-900',
'group inline-flex items-center rounded-md bg-white text-base font-medium hover:text-primary focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2'
]"
#mouseover="(e) => hoverPopover(e, open)"
#mouseleave="closePopover(close)"
>
<span v-if="!hasHref">{{ props.label }}</span>
<span v-else>
<NuxtLink :to="href">
{{ props.label }}
</NuxtLink>
</span>
<IconsChevronDown
:class="[
open ? 'rotate-180 transform text-primary' : '',
' ml-1 h-5 w-5 text-primary transition-transform group-hover:text-primary'
]"
aria-hidden="true"
/>
</PopoverButton>
<transition
enter-active-class="transition ease-out duration-200"
enter-from-class="opacity-0 translate-y-1"
enter-to-class="opacity-100 translate-y-0"
leave-active-class="transition ease-in duration-150"
leave-from-class="opacity-100 translate-y-0"
leave-to-class="opacity-0 translate-y-1"
>
<PopoverPanel
class="absolute left-1/2 z-10 mt-3 ml-0 w-auto min-w-[15rem] -translate-x-1/2 transform px-2 sm:px-0"
#mouseover.prevent="popoverHover = true"
#mouseleave.prevent="closePopover(close)"
>
<div
class="overflow-hidden rounded-lg shadow-lg ring-1 ring-black ring-opacity-5"
>
<div class="relative grid gap-1 bg-white p-3">
<slot> put content here </slot>
</div>
</div>
</PopoverPanel>
</transition>
</Popover>
</template>

It is in the docs:showing-hiding-popover.
open is an internal state used to determine if the component is shown or hidden. To implement your own functionality, you can remove it and use the static prop to always render a component. Then you can mange the visibility with your own state ref and a v-if/v-show. The mouse-action has to be in the upper scope, so it is not triggered leaving the component, e.g. moving the mouse from button to panel.
Below is a modified example from the API documentation:
<template>
<Popover
#mouseenter="open = true"
#mouseleave="open = false"
#click="open = !open"
>
<PopoverButton #click="open = !open">
Solutions
<ChevronDownIcon :class="{ 'rotate-180 transform': open }" />
</PopoverButton>
<div v-if="open">
<PopoverPanel static>
Insights
Automations
Reports
</PopoverPanel>
</div>
</Popover>
</template>
<script setup>
import { ref } from 'vue';
import { Popover, PopoverButton, PopoverPanel } from '#headlessui/vue';
import { ChevronDownIcon } from '#heroicons/vue/20/solid';
const open = ref(false);
</script>

Related

fixed element not filling the full width of the screen tailwind

I'm trying to fill the width of a fixed element in Tailwind to full width.
here's a screenshot of the modal:
Modal Screenshot
please ignore the text inside it as I'm still testing stuff out.
my code React:
import { Dialog, Transition } from '#headlessui/react'
import { Fragment, useState } from 'react'
import { Link } from 'react-router-dom'
export default function Modal2() {
let [isOpen, setIsOpen] = useState(true)
function closeModal() {
setIsOpen(false)
}
function openModal() {
setIsOpen(true)
}
return (
<>
<div className=" absolute right-1 top-5 p-2">
<button
type="button"
onClick={openModal}
className="flex rounded-3xl pl-6 pr-6 bb p-2 "
>
Open dialog
</button>
</div>
<Transition appear show={isOpen} as={Fragment}>
<Dialog as="div" className="relative z-10 " onClose={closeModal}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed flex inset-0 bg-black bg-opacity-80 blur2 " />
</Transition.Child>
<div className="fixed top-20 right-2 overflow-y-auto ">
<div className="flex justify-center p-4 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="mb-10 w-full max-w-md transform overflow-hidden rounded-3xl bg-white p-6 text-left align-top shadow-xl transition-all">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-gray-900"
>
Lorem, ipsum dolor.
</Dialog.Title>
<div className="mt-2">
<p className=" flex flex-col text-md text-gray-500">
<Link to={"/about"} className="py-1 ">dada</Link>
<span className='h bg-red-600'></span>
<Link className="py-1 " to={""}>dada</Link>
<span className='h bg-red-600'></span>
<Link className="py-1 " to={""}>dada</Link>
<span className='h bg-red-600'></span>
<Link className="py-1 " to={""}>dada</Link>
</p>
</div>
<div className="mt-4">
<button
type="button"
className="inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
onClick={closeModal}
>
Got it, thanks!
</button>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
</>
)
}
this is the line that opens the Modal. I want to make the width stretch to full-screen width. :
<div className="fixed flex inset-0 bg-black bg-opacity-80 blur2 " />
I would appreciate any help.
I tried to use items-stretch and w-full. didn't work. I guess its because it's fixed.
I couldn't reproduce your problem exactly, so this might be off.
If I understand your goal correctly, you're targeting the wrong element. The Dialog component contains your modal, so that's the component which should
have display: flex and justify-content: center to centralize the modal horizontally.
So you should add the classes flex and justify-center to the Dialog component. You can also add items-center to centralize it vertically.
[...]
<Transition appear show={isOpen} as={Fragment}>
<Dialog as="div" className="relative z-10 flex justify-center" onClose={closeModal}>
[...]

Navbar component works in normal cases but breaks incase of getstatic props

I am trying to make a page with getstaticprops but I am unable to include my navbar component in it as console screams out element type is invalid. I can use the same navbar component during normal page rendering without static or server props. my staticprops page
import {Navbar} from "../components/schema/Navbar"
export default function Dope({users}) {
console.log(users)
return (
<div>
{/* <Navbar /> */}
<main>
<div>
{users.length === 0 ? (
<h2>No users added</h2>
) : (
users.map((user, i) => (
<h1 key={i}>{user}</h1>
))
)}
</div>
</main>
</div>
)
}
export async function getStaticProps(ctx) {
// get the current environment
let dev = process.env.NODE_ENV !== 'production';
let { DEV_URL, PROD_URL } = process.env;
// request posts from api
let response = await fetch(`${dev ? DEV_URL : PROD_URL}/api/users`);
// extract the data
let data = await response.json();
return {
props : {
users : data['message']
}
}
}
my navbar component is too big to fit in here but it returns a regular navbar without any fetch operations and uses tailwindcss where as I did not make use of tailwind to style this page yet. can this be the reason? although I feel it isn't
the api endpoint works fine as well.
Edit:
my navbar is using Popover(panel, button, group), transition elements from headlessui
and Fragment from react
import { Fragment } from 'react'
import { Popover, Transition } from '#headlessui/react'
import {
BookmarkAltIcon,
CalendarIcon,
ChartBarIcon,
CursorClickIcon,
MenuIcon,
RefreshIcon,
ShieldCheckIcon,
SupportIcon,
ViewGridIcon,
XIcon,
} from '#heroicons/react/outline'
import { ChevronDownIcon } from '#heroicons/react/solid'
const features = [
{
name: 'Airdrops',
href: '#',
description: 'Get a better understanding of where your traffic is coming from.',
icon: ChartBarIcon,
},
{
name: 'Updates',
href: '#',
description: 'Speak directly to your customers in a more meaningful way.',
icon: CursorClickIcon,
},
{ name: 'Airdrop Tracer', href: '#', description: "Your customers' data will be safe and secure.", icon: ShieldCheckIcon },
{
name: 'FAQ',
href: '#',
description: "Connect with third-party tools that you're already using.",
icon: ViewGridIcon,
},
{
name: 'About',
href: '#',
description: 'Build strategic funnels that will drive your customers to convert',
icon: RefreshIcon,
},
]
const resources = [
{
name: 'Help Center',
description: 'Get all of your questions answered in our forums or contact support.',
href: '#',
icon: SupportIcon,
},
{
name: 'Guides',
description: 'Learn how to maximize our platform to get the most out of it.',
href: '#',
icon: BookmarkAltIcon,
},
{
name: 'Events',
description: 'See what meet-ups and other events we might be planning near you.',
href: '#',
icon: CalendarIcon,
},
{ name: 'Security', description: 'Understand how we take your privacy seriously.', href: '#', icon: ShieldCheckIcon },
]
function classNames(...classes) {
return classes.filter(Boolean).join(' ')
}
export default function Navbar() {
return (
<div className="relative bg-gray-50">
<Popover className="relative bg-white shadow">
<div className="max-w-7xl mx-auto px-4 sm:px-6">
<div className="flex justify-between items-center py-6 md:justify-start md:space-x-10">
<div className="flex justify-start lg:w-0 lg:flex-1">
<a href="#">
<span className="sr-only">Workflow</span>
<img
className="h-8 w-auto sm:h-10"
src="https://tailwindui.com/img/logos/workflow-mark-indigo-600.svg"
alt=""
/>
</a>
</div>
<div className="-mr-2 -my-2 md:hidden">
<Popover.Button className="bg-white rounded-md p-2 inline-flex items-center justify-center text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500">
<span className="sr-only">Open menu</span>
<MenuIcon className="h-6 w-6" aria-hidden="true" />
</Popover.Button>
</div>
<Popover.Group as="nav" className="hidden md:flex space-x-10">
<a href="#" className="text-base font-medium text-gray-500 hover:text-gray-900">
Airdrops
</a>
<a href="#" className="text-base font-medium text-gray-500 hover:text-gray-900">
Potential Airdrops
</a>
<a href="#" className="text-base font-medium text-gray-500 hover:text-gray-900">
Airdrop Tracer
</a>
<Popover className="relative">
{({ open }) => (
<>
<Popover.Button
className={classNames(
open ? 'text-gray-900' : 'text-gray-500',
'group bg-white rounded-md inline-flex items-center text-base font-medium hover:text-gray-900 focus:outline-none'
)}
>
<span>More</span>
<ChevronDownIcon
className={classNames(
open ? 'text-gray-600' : 'text-gray-400',
'ml-1 mt-2 h-5 w-5 group-hover:text-gray-500'
)}
aria-hidden="true"
/>
</Popover.Button>
<Transition
as={Fragment}
enter="transition ease-out duration-200"
enterFrom="opacity-0 translate-y-1"
enterTo="opacity-100 translate-y-0"
leave="transition ease-in duration-150"
leaveFrom="opacity-100 translate-y-0"
leaveTo="opacity-0 translate-y-1"
>
<Popover.Panel className="absolute left-1/2 z-10 transform -translate-x-1/2 mt-3 px-2 w-screen max-w-md sm:px-0">
<div className="rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 overflow-hidden">
<div className="relative grid gap-6 bg-white px-5 py-6 sm:gap-8 sm:p-8">
{resources.map((item) => (
<a
key={item.name}
href={item.href}
className="-m-3 p-3 flex items-start rounded-lg hover:bg-gray-50"
>
<item.icon className="flex-shrink-0 h-6 w-6 text-indigo-600" aria-hidden="true" />
<div className="ml-4">
<p className="text-base font-medium text-gray-900">{item.name}</p>
<p className="mt-1 text-sm text-gray-500">{item.description}</p>
</div>
</a>
))}
</div>
</div>
</Popover.Panel>
</Transition>
</>
)}
</Popover>
</Popover.Group>
<div className="hidden md:flex items-center justify-end md:flex-1 lg:w-0">
<a href="#" className="whitespace-nowrap text-base font-medium text-gray-500 hover:text-gray-900">
Sign in
</a>
<a
href="#"
className="ml-8 whitespace-nowrap inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-indigo-600 hover:bg-indigo-700"
>
Sign up
</a>
</div>
</div>
</div>
<Transition
as={Fragment}
enter="duration-200 ease-out"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="duration-100 ease-in"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Popover.Panel
focus
className="absolute top-0 inset-x-0 z-10 p-2 transition transform origin-top-right md:hidden"
>
<div className="rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 bg-white divide-y-2 divide-gray-50">
<div className="pt-5 pb-6 px-5">
<div className="flex items-center justify-between">
<div>
<img
className="h-8 w-auto"
src="https://tailwindui.com/img/logos/workflow-mark-indigo-600.svg"
alt="Workflow"
/>
</div>
<div className="-mr-2">
<Popover.Button className="bg-white rounded-md p-2 inline-flex items-center justify-center text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500">
<span className="sr-only">Close menu</span>
<XIcon className="h-6 w-6" aria-hidden="true" />
</Popover.Button>
</div>
</div>
<div className="mt-6">
<nav className="grid gap-y-8">
{features.map((item) => (
<a
key={item.name}
href={item.href}
className="-m-3 p-3 flex items-center rounded-md hover:bg-gray-50"
>
<item.icon className="flex-shrink-0 h-6 w-6 text-indigo-600" aria-hidden="true" />
<span className="ml-3 text-base font-medium text-gray-900">{item.name}</span>
</a>
))}
</nav>
</div>
</div>
<div className="py-6 px-5 space-y-6">
<div>
<a
href="#"
className="w-full flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-indigo-600 hover:bg-indigo-700"
>
Sign up
</a>
<p className="mt-6 text-center text-base font-medium text-gray-500">
Existing customer?
<a href="#" className="text-indigo-600 hover:text-indigo-500">
Sign in
</a>
</p>
</div>
</div>
</div>
</Popover.Panel>
</Transition>
</Popover>
</div>
)
Could you show us the Navbar code as well? can't really say what's going wrong without taking a look at the code.
Edit:
The problem is, when you import the Navbar component you are using a named import (an import with curly braces), and your Navbar component
is a default export, so you should use a default import like so:
import Navbar from "../components/schema/Navbar"
notice there are no curly braces.
check out this blog post -https://vhudyma-blog.eu/2020-09-27-default-vs-named-export-what-is-the-difference/
I was importing the function Navbar in a wrong manner. I was destructuring Navbar during import where as it should be a normal import

react modal unable to open

i am trying to use the headless ui modal but i am trying to launch this modal.js from my home.js file.
so in my home.js file i have something like this
function Home() {
const [isOpen, setIsOpen] = useState(false)
const resultCKDArr = Object.values(responseData.ckd).map((item, i)=>
<section class="text-gray-600 body-font overflow-hidden">
<div class="container px-5 py-10 mx-auto">
<button onClick={() => setIsOpen(!isOpen)} class="flex ml-auto text-white bg-indigo-500 border-0 py-2 px-6 focus:outline-none hover:bg-indigo-600 rounded">Buy List</button>
</div>
<Modal isOpen={isOpen} setIsOpen={setIsOpen} />
</section>
)
return (
<>
{resultCKDArr }
</>
);
export default Home;
and this is my modal.js copy from headless ui modal as example to test
import React, { Fragment } from "react";
import { Dialog, Transition } from '#headlessui/react'
export default function Modal( props ) {
const { isOpen, setIsOpen } = props
return (
<Transition appear show={isOpen} as={Fragment}>
<Dialog as="div" className="relative z-10" onClose={setIsOpen}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-4 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-gray-900"
>
Payment successful
</Dialog.Title>
<div className="mt-2">
<p className="text-sm text-gray-500">
Your payment has been successfully submitted. We’ve sent
you an email with all of the details of your order.
</p>
</div>
<div className="mt-4">
<button
type="button"
className="inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
onClick={setIsOpen}
>
Got it, thanks!
</button>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
)
};
maybe this is the error i saw in console
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
when i click on the button, i nothing happen, no modal pop out.
In my case there was an error with Dialog.Panel component. Try changing it to a div.

How to set and unset cookies using AlpineJS and Tailwind Toggle

I have the following code that uses tailwindcss for the toggle, and AlpineJS for adding a cookie base on the toggle state (on/off).
But I can't seem to make it work.
Here's the codepen: https://codepen.io/williamharvey/pen/GRMBqzO
Any help or direction will be appreciated
Thanks
And here's the code.
<div
class="flex w-full items-center bg-gray-100 border-b border-gray-200 px-5 py-3 text-sm"
x-data="{ cookieConcent1: docCookies.getItem('cookieConcent1') === 'true'} "
x-init="$watch('!cookieConcent1', val => docCookies.setItem('cookieConcent1', val))"
x-bind:class="{ 'cookieConcent1': cookieConcent1 }">
<div class="flex-1">
<p>Strictly necessary cookies</p>
</div>
<div class="w-10 text-right">
<button type="button"
class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-300 bg-gray-200"
x-data="{ on: true }"
role="switch"
aria-checked="false"
:aria-checked="on.toString()"
#click="on = !on;cookieConcent1 = !cookieConcent1"
x-state:on="Enabled"
x-state:off="Not Enabled"
:class="{ 'bg-green-400': on, 'bg-gray-200': !(on) }
">
<span class="sr-only">Use setting</span>
<span aria-hidden="true" class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200 translate-x-0"
x-state:on="Enabled"
x-state:off="Not Enabled"
:class="{ 'translate-x-5': on, 'translate-x-0': !(on) }
"></span>
</button>
</div>
</div>

Alpinejs Accordion and Toggle on click

I’m using Alpinejs and Tailwind.
I'm trying to create an accordion with a toggle on each tab, but I want that toggle to trigger at the same time as when a user clicks to open each part of the accordion... here's what I got so far:
<ul class="block mb-4" x-data="{pay:null}">
<li class="flex flex-col">
<div #click="pay !== 'cc' ? pay = 'cc' : pay = null" class="cursor-pointer px-5 py-3 flex items-center bg-blue-50 border text-xl font-semibold border-blue-800 text-blue-800 inline-block hover:shadow rounded-t">
<button type="button" class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-500 bg-gray-200" x-data="{ on: false }" aria-pressed="false" :aria-pressed="on.toString()" #click="on = !on" x-state:on="Enabled" x-state:off="Not Enabled" :class="{ 'bg-orange-500': on, 'bg-white': !(on) }">
<span class="sr-only">Credit Card</span>
<span aria-hidden="true" class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200 translate-x-0" x-state:on="Enabled" x-state:off="Not Enabled" :class="{ 'translate-x-5': on, 'translate-x-0': !(on) }"></span>
</button>
<span class="ml-2">Credit / Debit Card</span>
</div>
<p x-show="pay == 'cc'" class="bg-white border-l border-r border-blue-800 py-4 px-2">
This is made with Alpine JS and Tailwind CSS
</p>
</li>
<li class="flex align-center flex-col">
<h4 #click="pay !== 1 ? pay = 1 : pay = null" class="cursor-pointer px-5 py-3 bg-indigo-400 text-white text-center inline-block hover:opacity-75 hover:shadow hover:-mb-3">Accordion item 2</h4>
<p x-show="pay == 1" class="border py-4 px-2">
There's no external CSS or JS
</p>
</li>
<li class="flex align-center flex-col">
<h4 #click="pay !== 2 ? pay = 2 : pay = null" :class="{'cursor-pointer px-5 py-3 bg-indigo-500 text-white text-center inline-block hover:opacity-75 hover:shadow hover:-mb-3': true, 'rounded-b': pay != 2}">Accordion item 3</h4>
<p x-show="pay == 2" :class="{'border py-4 px-2': true, 'rounded-b': pay == 2}">
Pretty cool huh?
</p>
</li>
</ul>
https://codepen.io/kennyk3/pen/eYBwEXN
I'm pretty green, so bear with me. I actually just want to comment but don't have enough reputation.
First of all, you need to remove bg-gray-200 from your <button class> because you're binding :class="{ bg-{color} } for on: true and on: false states. Another one is bg-orange-500 and ring-orange-500 isn't a defined utility on Tailwind CSS. Maybe you mean bg-yellow-500 and ring-yellow-500? Other than that, what is x-state? I can't find it in Alpine.js docs.
Okay, about your requested problem, your code actually has 2 issues.
You want a parent component to communicate with a child component, like a nested component. Alpine.js doesn't do that. Either you merge both components holding multiple properties in the parent component so that you only have one x-data or you $dispatch('customEvent') on your <div> at the #click event (together with pay toggling) and listen to the #customEvent.window on your <button> component.
Alternatively, you can install Alpine Magic Helpers for the $component/$parent communication or install Spruce for saving all states.
Because of your <button> is nested in your <div>, you're firing both #click events every time you #click the <button>. This is why your code looks like the <button> component communicates with your <ul> component which is untrue. You're firing two different #click events. Because of this behavior, if you $dispatch('customEvent') from your <div> component and listen to the #customEvent.window on your <button>, you'll end up toggling your on state twice. Try add #click.debounce.250 on your <button> together with the #customEvent.window and you'll see it toggles to and fro.
As for that, you need to remove #click event on your <button> while listening to the #customEvent.window so that the toggling happens once, or better you merge both x-data making your <ul> holding multiple properties (no need to $dispatch('customEvent') on your <div> and #click on your <button>, just one #click on your <div>).
In my implementation, I make x-data to hold both:
<ul class="block mb-4" x-data="{pay:null, on: false}">
<li class="flex flex-col">
<div #click="pay !== 'cc' ? pay = 'cc' : pay = null, on = !on" class="cursor-pointer px-5 py-3 flex items-center bg-blue-50 border text-xl font-semibold border-blue-800 text-blue-800 inline-block hover:shadow rounded-t">
<button type="button" class="relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-yellow-500" aria-pressed="false" :aria-pressed="on.toString()" x-state:on="Enabled" x-state:off="Not Enabled" :class="{ 'bg-yellow-500': on, 'bg-gray-200': !(on) }">
<span class="sr-only">Credit Card</span>
<span aria-hidden="true" class="pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200 translate-x-0" x-state:on="Enabled" x-state:off="Not Enabled" :class="{ 'translate-x-5': on, 'translate-x-0': !(on) }"></span>
</button>
<span class="ml-2">Credit / Debit Card</span>
</div>
<p x-show="pay == 'cc'" class="bg-white border-l border-r border-blue-800 py-4 px-2">
This is made with Alpine JS and Tailwind CSS
</p>
</li>
<li class="flex align-center flex-col">
<h4 #click="pay !== 1 ? pay = 1 : pay = null" class="cursor-pointer px-5 py-3 bg-indigo-400 text-white text-center inline-block hover:opacity-75 hover:shadow hover:-mb-3">Accordion item 2</h4>
<p x-show="pay == 1" class="border py-4 px-2">
There's no external CSS or JS
</p>
</li>
<li class="flex align-center flex-col">
<h4 #click="pay !== 2 ? pay = 2 : pay = null" :class="{'cursor-pointer px-5 py-3 bg-indigo-500 text-white text-center inline-block hover:opacity-75 hover:shadow hover:-mb-3': true, 'rounded-b': pay != 2}">Accordion item 3</h4>
<p x-show="pay == 2" :class="{'border py-4 px-2': true, 'rounded-b': pay == 2}">
Pretty cool huh?
</p>
</li>
</ul>
https://codepen.io/wanahmadfiras/pen/jOVgBrz
Accordions (among other components) are now part of official AlpineJS documentation. Use them for perfect out of the box accordions.

Categories

Resources