I’m working on a little app, where I go left while holding on a text/button.
HTML:
<h1 style="color:white;" id="goLeft">Left</h1>
JS:
document.querySelector('#goLeft').addEventListener('touchstart', function(){
simulateKeyDown('a')
})
document.querySelector('#goLeft').addEventListener('mousedown', function(){
simulateKeyDown('a')
})
document.querySelector('#goLeft').addEventListener('touchstop', function(){
simulateKeyUp('a')
})
document.querySelector('#goLeft').addEventListener('mouseup', function(){
simulateKeyUp('a')
})
Now while that works great on desktop (holding down on the h1 tag and releasing), it doesn’t fully work as intended on phone, which touch. When just touching the selector of a short time, so pressing "Left" for only a fraction of a second, it works. However, when holding on the left button for a bit longer and I release it afterwards, my characters keeps moving to the right, so the event never seems to be triggered. My best guess is that is because of a long touch on the element, as with being able to mark and copy something.
What I’ve tried is changing the h1
to a button, with no changes.
Also, I forbid user selection in CSS:
-webkit-user-select: none; /* Safari */
-ms-user-select: none; /* IE 10 and IE 11 */
user-select: none; /* Standard syntax */
That also didn’t change something for that specific behaviour, although I’ll leave it like that.
How can I prevent that "long touch" to be executed and make sure, that the touchstop event is actually fired, when I release the button/h1?
2
Answers
Okay, nevermind, seems like I solved it myself... It seems like
touchstop
is not the right event - instead it has to betouchend
- it works now! :)You should define a listener to touchend in order to works proper.
I did this in React + typescript, maybe you can adapt to your scenario.