Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. # Manually Triggering Attribute Machine Change
  2.  
  3. ## Background
  4.  
  5. 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.
  6.  
  7. You need to use `.dispatchEvent(new CustomEvent('change'))` in order for Attribute maMachine to respond.
  8.  
  9. ## Implimentation
  10.  
  11. Add the CustomEvent pollyfil to the `plugins.js` or to the specific js file if that's better.
  12.  
  13. ```js
  14. // --- Custom Event Polyfill --- //
  15. (function () {
  16. if ( typeof window.CustomEvent === "function" ) return false; //If not IE
  17.  
  18. function CustomEvent ( event, params ) {
  19. params = params || { bubbles: false, cancelable: false, detail: undefined };
  20. var evt = document.createEvent( 'CustomEvent' );
  21. evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
  22. return evt;
  23. }
  24.  
  25. CustomEvent.prototype = window.Event.prototype;
  26.  
  27. window.CustomEvent = CustomEvent;
  28. })();
  29. ```
  30.  
  31. Then instead of doing something like:
  32. ```js
  33. $('.size-dropdown').val('small').trigger('change');
  34. ```
  35.  
  36. Try this:
  37. ```js
  38. $('.size-dropdown').val('small');
  39. $('.size-dropdown')[0].dispatchEvent(new CustomEvent('change'));
  40. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement