41

I've very new to HTML/JavaScript but am learning…

I want to make a button on an iPhone that runs a JavaScript command when it is pressed and another when it is released. I tried to do this using onmousedown and onmouseup properties, but this does not work the same on iPhone.

<input type="image" onmousedown="command_press()" onmouseup="command_release()" src="images/UP-Dark.png" alt="" title="" />

Could someone please tell me how to do the same thing on the iPhone?

BarryCap
  • 326
  • 3
  • 11
user3175352
  • 411
  • 1
  • 4
  • 3

2 Answers2

48

The equivalent for onmousedown on touchscreen devices is ontouchstart, and the equivalent of onmouseup is ontouchend.

If you would also like to detect dragging, you could use ontouchmove which is fired every time you move your finger after touching the screen.

tckmn
  • 57,719
  • 27
  • 114
  • 156
  • 1
    Note this will fire twice if you use like `element.onmousedown = element.onkeydown = element.ontouchstart = function() { /* event handler... */ }`. Replacing the mouse and touch event with the `onpointerdown` instead, as [recommended in Zectbumo's answer](https://stackoverflow.com/a/50488754/1201863), fixes this problem. – Luc Mar 25 '22 at 16:47
40

You might be interested in onpointerup and onpointerdown events which will work on both touch and non touch devices. Check browser support

Zectbumo
  • 4,128
  • 1
  • 31
  • 26