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

Viewed 1429

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"`enter code here`
        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>
1 Answers

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>
Related