Seydina's avatar

Adding on click a class in any html element that is outside the scope of the x-data div using Alpine JS?

This a sample of x-data div :


<div x-data="{ show: false }">
    <button @click="show = !show" :aria-expanded="show ? 'true' : 'false'" :class="{ 'active': show }">
    X
  	</button>
    <div x-show="show">
      <input type="text">
    </div>
</div>

And this is the section I want to add the class :

<main id="main">
   <!-- Other content -->
</main>
0 likes
4 replies
Jsanwo64's avatar

try

<div x-data="{ show: false }">
    <button @click="show = !show" :aria-expanded="show ? 'true' : 'false'" :class="{ 'active': show }">
    X
    </button>
    <div x-show="show">
        <input type="text">
    </div>
</div>

<main id="main" x-data="{ show: false }" x-init="$watch('show', value => { if (value) { document.getElementById('main').classList.add('active'); } else { document.getElementById('main').classList.remove('active'); } })">
    <!-- Other contents can go into this space -->
</main>
PRESTIGE2930's avatar

alpine vaiables works in scopes trying to call a class outside its scope would not work, and even if u find a way to make it work, i dont think it will give the desired response everytime, does this help?.

Seydina's avatar

@PRESTIGE2930 Previously I achieve this with Javascript without problem. But because I use Laravel livewire with Breeze Starter Kit, the wire:navigate blocks my custom JS that's why I am migrating from Vanilla Javascript to Alpine JS. Some parts like dropdown profile, toggling search bar on click are rewritten in Alpine without problems but this part (the one who originated my request) is a bit hard.

Please or to participate in this conversation.