gerardw85's avatar

alpine.js - multiple drop downs in a navbar

Hi, I'm getting tripped up using alpine when I'm using two drop down menus in my nav bar.

<div
    x-data="{
            ActiveButton: false,
            toggle() {
                if (this.open) {
                    return this.close()
                }
                this.$refs.button.focus()
                this.open = true
            },
            close(focusAfter) {
                if (! this.open) return
                this.open = false
                focusAfter && focusAfter.focus()
            }
        }"
    @keydown.escape.prevent.stop="close($refs.button)"
    @focusin.window="! $refs.panel.contains($event.target) && close()"
    x-id="['dropdown-button']"
    class="relative bg-white"
    >

Button

                            <button
                                x-ref="button"
                                @click="ActiveButton = 1;toggle()"
                                :aria-expanded="open"
                                :aria-controls="$id('dropdown-button')"
                                type="button"
                                class="text-gray-500 group inline-flex items-center rounded-md bg-white text-base font-medium hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                            >

Panel

<div
                            x-ref="panel"
                            x-show="ActiveButton === 1"
                            x-transition.origin.top.left
                            @click.outside="close($refs.button)"
                            :id="$id('dropdown-button')"
                            style="display: none;"
{{--                            class="absolute left-0 mt-2 w-40 rounded-md bg-white shadow-md"--}}
                        >

Same thing for the second button, with Active Button set to 2. The above code opens the menu - but I can't close it.

Looks like @click can support two values, but not accept toggle() after setting ActiveButton's value?

Is there a different way to associate the button/panel while still calling @click?

0 likes
1 reply
angelcruzdev's avatar

I know, it's a little late but here's my two cents:

x-data="{
    activeButton: null,
    toggle(buttonId) {
        this.activeButton = this.activeButton === buttonId ? null : buttonId;
    },
    isActive(buttonId) {
        return this.activeButton === buttonId;
    },
    close() {
        this.activeButton = null;
    }
}"

then, in each button:

@click="toggle(1)"

and finally in your panels:

x-show="isActive(1)"

Please or to participate in this conversation.