Detect variant change outside theme.js

New Member
1 0 0

Hi,

 

I am trying to achieve the following:

Have a liquid snippet or javascript file within a theme that detects if a variant in a product page is changed, grab its' SKU and executes code each time this happens. Just like the _updateSKU event listener in the theme.js which is triggered by slate.Variants and the _updateSKU function. I know I could just add code in the theme.js, but I'd rather not as this code is more of an add-on.

 

I CAN achieve this by this approach where I let the theme.js update a span and grab the value via a mutation observer:

 

 

<span class="variant-sku" id="sku-container" style="display: none!important;width:0!important;height:0!important;">{{ variant.sku }}</span>

<script>
    
  const targetNode = document.getElementById('sku-container');
  
  let sku = targetNode.innerHTML;  

  const config = { attributes: true, childList: true, subtree: true };
  const callback = function(mutationsList, observer) {
      // Use traditional 'for loops' for IE 11
      for(let mutation of mutationsList) {
          if (mutation.type === 'childList') {
            sku = targetNode.innerHTML;
            _updateCode(sku);
          }        
      }
  };
  const observer = new MutationObserver(callback);
  observer.observe(targetNode, config);
  
  function _updateCode(sku){
    // do stuff
  }
    
  
</script>

 

 

But it seems a bit hacky.

 

Can someone provide me with a better approach? I'd love to just hook into the events provided by theme.js, but they do not seem to be accessible anywhere outside of the file.

 

Thanks!

0 Likes