Magento – Execute JavaScript code after swatches are displayed in category view

category-viewconfigurable-productmagento2swatches

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.

enter image description here

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>

Best Answer

I used the event 'swatch.initialized' to fire a function after swatches are loaded in the product page:

$(document).on('swatch.initialized', function() {
  // do something
})

The event is triggered in Magento_Swatches/js/swatch-renderer.js

$(this.element).trigger('swatch.initialized');
Related Topic