Created
September 21, 2020 14:30
-
-
Save lupinthe14th/cb1ee28c287cac7c1759b8f18cd232e5 to your computer and use it in GitHub Desktop.
Make Image Change javascript (for theme.js file)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| SeeAlso: | |
| - https://shopify.dev/tutorials/customize-theme-select-variants-by-clicking-images | |
| - https://gist.github.com/drabbytux/a49215c6d0ba16c4d096a56212bbc4ce | |
| - https://gist.github.com/drabbytux/7f3f2c57c01fcd4baba98668c9473adc | |
| To be placed at bottom of theme.js, or main JS file that doesn't use jquery. | |
| **/ | |
| document.addEventListener("DOMContentLoaded", function() { | |
| thumbnails = document.querySelectorAll('img[src*="/products/"]'); | |
| function addEventListenerList(thumbnails) { | |
| for (var i = 0, len = thumbnails.length; i < len; i++) { | |
| thumbnails[i].addEventListener('click', thumbImageSwap, false); | |
| } | |
| } | |
| addEventListenerList(thumbnails); | |
| function thumbImageSwap() { | |
| var arrImage = this.getAttribute('src').split('?')[0].split('.'); | |
| var strExtention = arrImage.pop(); | |
| var strRemaining = arrImage.pop().replace(/_[a-zA-Z0-9@]+$/, ''); | |
| var strNewImage = arrImage.join('.') + "." + strRemaining + "." + strExtention; | |
| if (typeof variantImages[strNewImage] !== 'undefined') { | |
| productOptions.forEach(function(value, i) { | |
| optionValue = variantImages[strNewImage]['option-' + i]; | |
| let selectors = document.querySelectorAll('.single-option-selector') | |
| if (typeof selectors[i] !== 'undefined') { | |
| let options = selectors[i].querySelectorAll('option'); | |
| let arrayOptions = [].map.call(options, (element) => { | |
| return element; | |
| }); | |
| let filterOptions = arrayOptions.filter(function(value) { | |
| return value.textContent === optionValue; | |
| }); | |
| if (optionValue !== null && filterOptions.length) { | |
| let el = document.querySelectorAll('.single-option-selector')[i]; | |
| el.value = optionValue; | |
| el.dispatchEvent(new Event('change')); | |
| }; | |
| }; | |
| }); | |
| }; | |
| }; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment