Last active
August 30, 2022 22:17
-
-
Save schappim/87f3720c5842c74d1bdf46e842d0ce68 to your computer and use it in GitHub Desktop.
This file contains 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
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script> | |
<script type="text/javascript"> | |
window.changeImageURLs = function() { | |
return { | |
changeTheURLs() { | |
// get the current product URL without the query string | |
var currentURL = window.location.href.split('?')[0]; | |
// find all images with the class product-single__thumbnail-image | |
var images = document.getElementsByClassName('product-single__thumbnail-image'); | |
console.log(images); | |
// loop through each image | |
Array.prototype.forEach.call(images, function(image) { | |
console.log(image) | |
// get the src attribute | |
let src = image.getAttribute('src'); | |
// get the variant id from the image src | |
let variantId = src.split('?v=')[1]; | |
// create a new url which is currentURL?variant=:VariantID | |
let newURL = currentURL + '?variant=' + variantId; | |
// get the a tag which wraps the image | |
let aTag = image.closest('a'); | |
// set the href attribute of the a tag to the new url | |
aTag.setAttribute('href', newURL); | |
// add @onlick="window.location.href = 'newURL'" to the a tag (just in case another script is being dodgey) | |
aTag.setAttribute('onclick', "window.location.href = '" + newURL + "'"); | |
}) | |
} | |
} | |
} | |
</script> | |
<div x-data="changeImageURLs()" x-init="changeTheURLs()"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment