I'm trying to trigger custom event whenever Magento displays the product swatches in category view.
It looks like Magento uses ajax to load these swatches, they are not displayed on page load, they "pop" after a few moments. I need to add some custom JavaScript code after these swatches are actually displayed. So I thought the best way will be to trigger custom event just after Magento finishes to render the swatches. But I'm not sure how to do this correctly in Magento 2.
What I want to do is to trigger a custom event $(document).trigger('swatches-visible');
when a block of swatches is finally displayed on the page.
And then, an event handler will execute a function:
$(document).on('swatches-visible', function() {
doSomething();
});
That function doSomething()
is already added via RequireJS in one of the template files:
<script type="text/javascript">
requirejs(['jquery'], function(jQuery) {
function doSomething()
{
// Here make some layout changes of the products list...
}
});
</script>
$(document).trigger('swatches-visible')
when a block of swatches is finally displayed. And then, an event handler will execute a function:$(document).on('swatches-visible', function(e) { doSomething(); });
That functiondoSomething()
is already added via RequireJS in one of the template files. What you proposed sounds like a good solution but I'm not sure how to use it in my case. Isn'tdata-mage-init
executed only on page load? Note that the blocks of swatches for all products, e.g.<div class="swatch-opt-1822">...</div>
, are displayed with a delay, not instantly on page load.data-mage-init
is,x-magento-init
is different although I'm not sure if that is also only on page load (the dev docs don't mention). If it is page load then the only other method I can think of is to initialise the JS inside the swatch template. Require works in templates to so I don't see why that wouldn't work.