On Android Chrome, when you create a new tab and access to a page with the content below, your touches to #touch div have never triggered touch-start events. Once you reload the page, you can trigger the event.
Why? and How can I avoid this situation?
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>touch start on Android</title> <style type="text/css"> #touch, #click { position: relative; left: 100px; top: 100px; width: 200px; height: 200px; border: solid 1px black; } </style> </head> <body> <div id="touch">Touch</div> <div id="click">Click</div> <script type="text/javascript"> document.getElementById('touch').addEventListener('touchstart', function () { alert ('touch'); } , false); document.getElementById('click').addEventListener('click', function () { alert('click'); } , false); </script> </body> </html>
Definition and Usage The touchstart event occurs when the user touches an element. Note: The touchstart event will only work on devices with a touch screen. Tip: Other events related to the touchstart event are: touchend - occurs when the user removes the finger from an element.
Just adding return false; at the end of the on("click touchstart") event function can solve this problem.
onTouchStart works only for mobile. Also, this event goes before the onClick event.
Maybe try to delay adding the event listeners until the DOM is ready?
<script> function touchTest() { document.getElementById('touch').addEventListener('touchstart', function () { alert ('touch'); } , false); document.getElementById('click').addEventListener('click', function () { alert('click'); } , false); } document.addEventListener('DOMContentLoaded', touchTest); </script>
The fact that your code works on a reload might indicate that the event listeners are being added too quickly on the first page load?
If 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