Reputation: 53
I have written an external JS script that shows a custom text on the stores product's page. Currently the JS function is called once, on the window.onload function.
I want my script to be able to detect a variant change and swap out the text to a different one, whenever a different variant is selected. How do I detect a variant change and get it's price in an external JS file, using only JS/jQuery function.
<script id="testscript" src="https://example.com/test.js?amount=${{ product.price | divided_by: 100.00 | round: 2 }}"></script>
<div id="mydiv"></div>
My code in test.js:
window.onload = function () {
document.getElementById("mydiv").innerHTML += ("<p>This is a test.</p>");
};
Upvotes: 3
Views: 3765
Reputation: 447
It depends on how your theme structure looks like. Let's assume you are using Debut theme:
https://debut-demo.myshopify.com/products/laptop-sleeve
You need to set an event listener on the element of your page that's responsible for variant change. On the page above it's a select that allows customers to change item size.
If you open page inspector and preview website code, select element has the following structure:
<select class="single-option-selector single-option-selector-product-template product-form__input" id="SingleOptionSelector-0" data-index="option1">
<option value="13”" selected="selected">13”</option>
<option value="15”">15”</option>
</select>
You can achieve it in to ways. First step is to create such function in your JS file:
function detectChange(element) {
var value = element.value;
var myDiv = document.getElementById("mydiv");
myDiv.innerHTML += `<p>${value}</p>`;
}
Then either add the function as event listener in select
element:
<select class="single-option-selector single-option-selector-product-template product-form__input" id="SingleOptionSelector-0" data-index="option1" onchange="detectChange(this)">
OR bind the listener to an element:
document.getElementById("SingleOptionSelector-0").addEventListener("change", detectChange(this));
Upvotes: 1