I am trying to understand touch events, but I cannot get anything to work.
I have a very simple page to test this:
HTML:
<div id="TOUCHME"> TOUCH ME </div>
<div id="OUTPUT"></div>
JavaScript:
const TOUCHME = document.getElementById('TOUCHME');
const OUTPUT = document.getElementById('OUTPUT');
TOUCHME.addEventListener('touchstart',(evt)=>{
evt.preventDefault();
let touches = evt.touches;
for(let i=0; i<touches.length; i++){
let newDiv = document.createElement('div');
newDiv.appendChild(document.createTextNode(touches[i]));
OUTPUT.appendChild(newDiv);
}
});
However, as you can guess, nothing shows up. I even referenced MDN and they have an almost identical example.
I found some information here on StackOverflow, but they say do something like this:
var touch = event.touches[0];
var x = touch.pageX;
var y = touch.pageY;
This does work, but what if a person doesn't know that touch[0] is what you need to access? Aside from scouring MDN, how is a person supposed to know all the properties of touch[0] unless they can iterate over the TouchList?
I also tried this:
Object.entries(evt.touches)
and
Object.entries(evt.touches[0])
But neither of those worked either; meaning I couldn't iterate over any list as their sizes are always 0.
So, how does a person iterate over the TouchList of touch properties for a touch?
You have to access the properties of the Touch event directly; destructuring assignments don’t seem to work here.
(i) If you are using a no-touch device, make sure to activate the touch simulation in your dev tools. For example, in Firefox this is done here: https://firefox-source-docs.mozilla.org/devtools-user/responsive_design_mode/#controlling-responsive-design-mode (search for “Enable/Disable touch simulation”)