learnvst learnvst - 1 month ago 13
HTML Question

Holdable html button on mobile Safari

I have a simple web button

<button id="awesome" style="height:150px; width:500px"></button>


And using safari on the desktop, I can do real time things in response to when the button is held down using . . .

document.getElementById('awesome').onmousedown = function() {
responding = true;
// console.log("on");
};

document.getElementById('awesome').onmouseup = function() {
responding = false;
// console.log("off");
};


But when I run this on Safari on the iPhone, holding the button makes the copy paste menu appear, and I do not get the behaviour I desire. What do I modify to get the same intended response across platforms?

Lee Lee
Answer

Because mobile phones don't have a mouse. The mobile browser will emulate some events just to provide a good experience for websites that haven't been optimised for mobile usage (such as the click event) but the two events you mentioned aren't emulated.

You will need to use touch events for mobile: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events

There's a few ways you can approach this:

  1. Look for library that does the event binding for you, there's probably a couple out there

  2. Detect the environment and bind one set of events or the other.

  3. Bind to both touch and mouse events. If a mouse event you want to use is being emulated you can either rely on the emulation for that one event, or preventDefault() and maybe stopPropagation in the appropriate touch event to stop the mouse event being triggered on mobile.