Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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.
- ```js
- // --- 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:
- ```js
- $('.size-dropdown').val('small').trigger('change');
- ```
- Try this:
- ```js
- $('.size-dropdown').val('small');
- $('.size-dropdown')[0].dispatchEvent(new CustomEvent('change'));
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement