There's a strange behavior on touch devices regarding the clickable area of a link, if you toggle the height of an element placed above. If you run the following snippet (e.g. save it locally and use chrome to emulate touch events), you will notice that the hash #mylink
is added to the url in some cases you did not click on the red link area. And sometimes you clicked the red area, it won't be added.
E.g.
#mylink
is added to the url as if you had clicked on the red link area. => Why?#mylink
is not added to the url. => Why?#mylink
is not added to the url. => Why?<html>
<head>
<style type="text/css">
.test {
background: grey;
height: 200px;
}
.test.is-visible {
height: 400px;
}
.link {
height: 600px;
display: block;
background: red;
}
</style>
<script type="text/javascript">
(function() {
window.addEventListener( 'touchstart' , function() {
document.getElementsByClassName("test")[0].classList.toggle('is-visible');
});
})();
</script>
</head>
<body>
<div class="test">
Click the grey area. Element enhances and minimizes itself. Now click on the lower half of the enhanced grey area (if grey = enhanced) or on the white area up to 200px below of the red area (if grey = minimized). #mylink is added to the url as if you had clicked on the red area. Why?
</div>
<a href="#mylink" class="link">The red area is the "normal" click area.</a>
</body>
</html>
I tried this on iOS, Android and emulated touch events in both Chrome and Firefox. They all behave the same.
If I listen to click
instead of touchstart
or touchend
event, it works as expected.
What's the reason for this discrepancy? Why is the link area different / misplaced if I listen to touch events instead of click event?
This is what happens when you enhanced the gray area and touch on the lower half:
touchstart
event is triggeredis-visible
class on the gray element200px
upwardstouchend
event is triggered on the red element, which is the event that determines if a link was touched or notThe same thing happens when you click on the area 200px
beneath the red element:
touchstart
event is triggeredis-visible
class on the gray element200px
downwardstouchend
event is triggered on the red element, which is the event that determines if a link was touched or notIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With