On touch devices the following events are triggered when touching an element:
The mouseenter, mousedown, mouseup and click events are emulated by the touchend event. If you want to disable this emulation of mouse events, preventDefault() can be used.
But if in iOS Safari I touch the edges of an element the following events are triggered:
Somehow the touch events are not triggered on the edges and because of this I also can't use preventDefault() to stop the emulation of the mouse events.
The problem occurs on both iPhone as iPad.
I searched Stack Overflow and Google, but I can't find anything about this. No bugs and no solutions. Does anybody know if this is a known bug in Safari?
I created the most basic code to reproduce this error in JSFiddle:
HTML:
<div id="element"></div>
<div id="log"></div>
CSS:
#element {
height: 100px;
width: 100px;
background: yellow;
margin: 20px;
}
JavaScript:
function handler(event) {
const log = document.getElementById('log');
log.innerHTML = `${event.type}<br />${log.innerHTML}`;
}
const element = document.getElementById('element');
element.addEventListener('mouseenter', handler);
element.addEventListener('mouseleave', handler);
element.addEventListener('mousedown', handler);
element.addEventListener('mouseup', handler);
element.addEventListener('click', handler);
element.addEventListener('focus', handler);
element.addEventListener('blur', handler);
element.addEventListener('touchstart', handler);
element.addEventListener('touchend', handler);
Try attaching the event listener to the outermost element, the html tag.
See more: https://www.tutorialrepublic.com/javascript-tutorial/javascript-event-propagation.php