I have found a very strange behavior that I cannot explain. Want to do the following:
A handler needs to react to a touchstart
or mouseover
event, depending on the type of input device. Note that I want to support hybrid devices (with both mouse and touchscreen) and I cannot rely on pointer events.
Now, I just setup both touchstart
and mouseover
events. And for the most part it works just fine. Also use preventDefault
to prohibit simulated "mouse" events firing after touch events. But what is totally confusing to me is that sometimes there is a still a mouseover
event occuring, and if I remove the preventDefault, it even seems that the mouseover
is firing instead of a touchstart
. Why oh why is this happening?
Furthermore, this is reproducible with both Android and iOS! Though it seems to be more easily triggered with Android (using Chrome).
I have prepared a little testcase so you can try for yourselves. Note that this behavior seems only triggered when you tap somewhere on the border between the red DIV (which has the events) and the background. Just tapping in the center works 100%. And you may need more or less tries until it happens.
Any help greatly appreciated!
<!DOCTYPE html>
<html>
<head>
<title>Touchtest</title>
<style>
body {
background: #222;
color: white;
position: relative;
font-size: .9em;
font-family: Arial, Helvetica, sans-serif;
}
#test {
position: fixed;
top: 100px;
right: 100px;
bottom: 100px;
left: 100px;
background: red;
}
</style>
</head>
<body>
<div id="test"></div>
<script type="text/javascript">
function testEvent(event) {
console.log("testEvent", event);
if (event.type === "mouseover") {
alert("MOUSEOVER DETECTED");
}
event.preventDefault();
}
var ele = document.getElementById("test");
ele.addEventListener("touchstart", testEvent);
ele.addEventListener("mouseover", testEvent);
</script>
</body>
</html>