Home > Back-end >  Alpine JS: updating properties on a `$ref` object
Alpine JS: updating properties on a `$ref` object

Time:12-09

Is it possible to manipulate the styling properties of an HTML object with AlpineJS by accessing it through the $refs magic variable?

It seems that I can access the properties of the element, but I can't update them!?!? After pressing the button, nothing happens (from the user point of view). The shadow just stays in the same place.

I can see from the console-log that the function does run as expected, but as the log shows, the offsetLeft property doesn't change.

<style>
.shadow {
    color: rgba(256, 256, 256, 0.1);
    left: 500px;
}
</style>
<div x-data="{
    changeElement() {
        console.log ('shadow at', $refs.shadow.offsetLeft); // prints '500'
        $refs.shadow.offsetLeft = 20;
        console.log ('shadow at', $refs.shadow.offsetLeft); // still prints '500'!?!?!
    }
}">
    <button @click="changeElement()">Change Element</button>
    <div  x-ref="shadow"></div>
</div>

If $refs is the wrong way to approach this, then how do I manipulate the DOM using AlpineJS?

CodePudding user response:

This is not the issue with alpinejs. The reason why you cannot change offsetLeft is because this is a read only field.

In order to manipulate DOM elements in alpinejs, I suggest you use binding either style or class and you can manipulate the value of the class string by the state of your data value.

<div x-data="{ open: false }">
  <button x-on:click="open = ! open">Toggle Dropdown</button>
 
  <div :>
    Dropdown Contents...
  </div>
</div>

The same thing can be done with style object. So, ref magic is used only for querying DOM elements in alpinejs.

CodePudding user response:

As pointed out by @LazarNikolic, my problem isn't linked to Alpine. The $refs.shadow object is a JavaScript object, and offsetLeft is a read-only property >> https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft

The JavaScript inside the x-data attribute should read as follows:

changeElement() {
    console.log ('shadow at', $refs.shadow.offsetLeft); // prints '500'
    $refs.shadow.style.left = 20   'px'; // because in the real-world, 20 is a dynamic element
    console.log ('shadow at', $refs.shadow.offsetLeft); // prints '20'
}
  • Related