Say I have an button with a touchEnd
event listener. If I touch the button, slide my finger out of the button and then release touch, I'd like to "cancel" the touch event.
This behaves correctly if I do the following using onClick
:
buttonElement.addEventListener('click', function (event) {
if (event.target === this) {
// Do something
}
});
However, this doesn't work with "touchEnd" because event.target
points to the originating element (buttonElement
in this case), not to the element where I released touch.
Is there a better generic way to do this besides doing something like setting a flag on "touchMove"? Thanks!
Use the touch events: touchstart, touchmove, touchcancel, touchend. See the Apple docs.
Regardless, I don't think I'd try to cancel the event. On the event I would check the location of the "cursor" (finger) and if it was outside of the area, just not fire the function.