Visual feedback to user actions
Providing visual feedback enhances user experience. This guide demonstrates how to add opacity to an image when a checkbox is checked, comparing approaches with jQuery, Knockout.js (in Luma), and Alpine.js.
The base HTML for this example is:
With jQuery
Using jQuery, you would load a RequireJS module via data-mage-init or x-magento-init. The module would contain code similar to this to toggle the opacity-40 class on the image:
With Knockout
For Knockout, a view model scope is assigned using x-magento-init and Magento_Ui/js/core/app. The view model would include an observable property, such as isSelected, referenced in the DOM like this:
<input type="checkbox" id="<?= $escapedId ?>" value="1"
data-bind="checked: isChecked">
<img src="<?= $field->getMediaUrl() ?>
data-bind="css: {'opacity-40': isSelected}">
With Alpine.js
In Hyvä, Alpine.js handles this task efficiently, often without needing external JavaScript files:
<div x-data="{ isSelected: true }">
<input type="checkbox" id="<?= $escapedId ?>" value="1" x-model="isSelected">
<img src="<?= $field->getMediaUrl() ?>" :class="{ 'opacity-40': isSelected}">
</div>
Alternatively, using Alpine.js with a more "vanilla" JavaScript approach:
<?php
// generate a unique JS property name (has to start with a character)
$refId = $escaper->escapeHtmlAttr('i' . md5($escapedId)); ?>
<input type="checkbox" id="<?= $escapedId ?>" value="1"
x-on:change="$refs.<?= $refId ?>.classList.toggle('opacity-40')">
<img src="<?= $field->getMediaUrl() ?>"
x-ref="<?= $refId ?>">
Alpine.js's x-ref directive simplifies such interactions, requiring minimal JavaScript.