I'm trying to write a script that adds an item to the cart by simulating a click on the add-to-cart button on a webpage
<span id="cart-update">
<span class="cart-button">add to basket</span>
</span>
When I try to do the following on desktop, it works perfectly
document.getElementById('cart-update').click();
But when I try doing the same thing on iPhone it doesn't work. I tried using the advice from this answer (Simulate click event on mobile device) and it didn't seem to work. Can you help me out?
Have you tried monitoring touch events at all, instead of click events? Mobile browsers have their own events they're monitoring, some not considering "click" as an event at all
From: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
function startup() {
var el = document.getElementsByTagName("button")[0];
el.addEventListener("touchstart", handleStart, false);
el.addEventListener("touchend", handleEnd, false);
el.addEventListener("touchcancel", handleCancel, false);
el.addEventListener("touchmove", handleMove, false);
console.log("initialized.");
}
A way to work around it would be for a click/touch event to trigger a separate function entirely, like calling handleStart() in your function triggering the click event. Might be a better separation of concerns, too.