This script works great as a stock countdown, but I can't display it in more than 1 spot on the same page.
For example, there are 4 or 5 products/plans on the same page, each product displays a different inventory quantity, and the time when the quantity changes is also different. Shown on only 1 product.
<span class="qty" id="qty"></span> <script> const setQty = (qty) => { qtySpan.innerHTML = qty; if (qty == 0) return; let parts = Math.floor((Math.random() * 3) + 1); if (parts > qty) parts = qty; const msec = Math.floor(((Math.random() * 15) + 15) * 1000); qty -= parts; // Save the updated quantity in localStorage localStorage.setItem('saved_countdown', qty); setTimeout(() => setQty(qty), msec); } // Get the saved countdown value from localStorage, or use default value of 57 if not found const defaultQty = localStorage.getItem('saved_countdown') ?? 57; const qtySpan = document.getElementById('qty'); // Set the initial value of the quantity setQty(defaultQty); </script>
I copied the script 4x and changed the ID "qty" to qty1, qty2, qty3 and qty4 but it doesn't work, it only shows up in 1 product...:/
Can anyone here help me? Thanks!
I changed the functionality so that you can have multiple countdowns.
You just send the specific number for each countdown as the second parameter.
I've modified your script to a custom element. This means you can now create an element called
<stock-counter>
.This element has 2 attributes,
quantity
andstorage-key
.quantity
is the amount to start counting from.storage-key
is the name of the local storage key used to store the last count for this specific counter. If a storage key is set and a storage value is found, that value replaces thequanitity
value, unless the storage value is0
.So the element looks like this:
You can place any number of these elements on the page and modify the
quantity
andstorage-key
of each element.