Aman
Aman

Reputation: 51

Alpinejs x-on:click not working, attaching it to a parent div item

I cannot get the console log after clicking on this element.However changing div to button will fetch result. Here is my code snippet.

    <div class="navbar">
      <div x-on:click="console.log('clicked')" class="navitem msn">
        <div>
          <svg
            xmlns="http://www.w3.org/2000/svg"
            class="h-6 w-6"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
            />
          </svg>
          <div class="navtitle">Title1</div>
        </div>
      </div>
</div>

Upvotes: 5

Views: 10279

Answers (3)

Choc.
Choc.

Reputation: 68

I'm also confused as to why it's not working. Until I saw this post and saw this:

Everything in Alpine starts with the x-data directive.

( from: https://alpinejs.dev/directives/data)

So instead of:

<div>
<button x-on:click="console.log('clicked')">...</button>
</div>

We need:

<div x-data>
<button x-on:click="console.log('clicked')">...</button>
</div>

To make it work!

Upvotes: 2

You need an empty x-data in any parent HTML tag, this should be enough. They should've mentioned that on the docs tough.

Upvotes: 3

Dauros
Dauros

Reputation: 10502

You have a couple of errors:

  • No x-data directive. You need at least an empty x-data on any Alpine.js component.
  • There's a random "enter code here" string in the SVG code.
  • You have a missing </div> element.

The corrected example:

<div x-data="" class="navbar">
  <div x-on:click="console.log('clicked')" class="navitem msn">
    <div>
      <svg
        xmlns="http://www.w3.org/2000/svg"
        class="h-6 w-6"
        fill="none"
        viewBox="0 0 24 24"
        stroke="currentColor"
      >
        <path
          stroke-linecap="round"
          stroke-linejoin="round"
          stroke-width="2"
          d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
        />
      </svg>
      <div class="navtitle">Title1</div>
    </div>
  </div>
</div>

Upvotes: 19

Related Questions