steveosoule
6/23/2017 - 10:33 PM

Manually Triggering Attribute Machine Change

Manually Triggering Attribute Machine Change

Manually Triggering Attribute Machine Change

Background

Changing the value of a product attribute (dropdown, radio, etc.) using JavaScript (ex: $('.dropdown').val('foo')) will not trigger the change event to fire Attribute Machine and load the new variant's information. Adding $('.dropdown').trigger('change') won't work either.

You need to use .dispatchEvent(new CustomEvent('change')) in order for Attribute maMachine to respond.

Implimentation

Add the CustomEvent pollyfil to the plugins.js or to the specific js file if that's better.

// --- Custom Event Polyfill --- //
(function () {
  if ( typeof window.CustomEvent === "function" ) return false; //If not IE

  function CustomEvent ( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
   }

  CustomEvent.prototype = window.Event.prototype;

  window.CustomEvent = CustomEvent;
})();

Then instead of doing something like:

$('.size-dropdown').val('small').trigger('change');

Try this:

$('.size-dropdown').val('small');
$('.size-dropdown')[0].dispatchEvent(new CustomEvent('change'));