Search code examples
onclickhidealpine.js

alpine.js, how to make element disappear on self @click?


I want this element to self hide once clicked. How do I target self with Alpine, and string 2 @click events together?

<div @click="tagify.addTags(['hardware'])">hardware</div>

Solution

  • There are multiple ways you can handle this,

    you can target self by the event.target as in method 1, other methods a just alternative approaches to hide the element.

    Method 1 - Set the style inline in the click handler

    <div @click="tagify.addTags(['hardware']); event.target.style.display='none';">hardware</div>
    
    

    Method 2 - Use x-ref

    <div x-ref="hardware" @click="tagify.addTags(['hardware']); $refs.hardware.style.display='none';">hardware</div>
    
    

    Method 3 - Use x-show with a variable

    <div x-data="{showHardware : true}">
        ....
        <div x-show="showHardware" @click="tagify.addTags(['hardware']); showHardware = false">hardware</div>
    </div>