I am trying to create a touch event for a unit test. After reading https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent, I expected that I would be able to do:
Update: This will not actually result in an instance of TouchEvent. lame.
I did it like this:
var type = 'start'; // or move, end
var event = document.createEvent('Event');
event.initEvent('touch' + type, true, true);
event.constructor.name; // Event (not TouchEvent)
You'll also need to set the touches on the event. That's another can of worms as some browsers support the document.createTouch and document.createTouchList methods and some don't. In browsers that don't you just create and array of JS objects that are "TouchEvent-like". This looks like:
var point = {x: 10, y: 10 };
event.touches = [{
target: someElement,
identifier: Date.now() + i,
pageX: point.x,
pageY: point.y,
screenX: point.x,
screenY: point.y,
clientX: point.x,
clientY: point.y
}]