manually trigger touch event

According to W3C

var e = document.createEvent('TouchEvent');

Then, also change

e.initMouseEvent();

to

e.initTouchEvent();

As you’ve created a touchstart event.

The W3C link says:

Some user agents implement an initTouchEvent method as part of the TouchEvent interface. When this method is available, scripts can use it to initialize the properties of a TouchEvent object, including its TouchList properties (which can be initialized with values returned from createTouchList). The initTouchEvent method is not yet standardized, but it may appear in some form in a future specification.

So you’ll might have to resort to e.initUIEvent('touchstart', true, true);
In addition, the official spec also states that the TouchList object is optional, and can be created manually using the createTouchList method. To add a touch to that list, you’ll have to call the createTouch method, where you’ll pass all coordinates and such:

6.1 Methods

#createTouch
Creates a Touch object with the specified attributes.
Parameter | Type        | Nullable | Optional | Description
view      | WindowProxy |   ✘      |    ✘     |
target    | EventTarget |   ✘      |    ✘     |
identifier| long        |   ✘      |    ✘     |
pageX     | long        |   ✘      |    ✘     |
pageY     | long        |   ✘      |    ✘     |
screenX   | long        |   ✘      |    ✘     |
screenY   | long        |   ✘      |    ✘     |
Return type: Touch

#createTouchList
Creates a TouchList object consisting of zero or more Touch objects. Calling this method with no arguments creates a TouchList with no objects in it and length 0 (zero).

Parameter | Type  | Nullable | Optional | Description
touches   | Touch |     ✘    |    ✔     |
Return type: TouchList

If that doesn’t work, you could try this:

var e = document.createEvent('UIEvent');
e.initUIEvent();

should work, it makes more sense than createEvent('MouseEvent') at any rate…
But for testing purposes, why not open your chrome console and check Emulate touch events, plus override user agent to Android 4. (Ctrl+Shift+j > click the gear bottom right corner, and select Overrides, there you’ll find all the settings you need)

Since the touch-events have a long way to go, still in terms of their becoming standardized, it turns out the touches property is not RO (yet?), so you can use this quick-fix (which the OP found and used with the desired result):

var e = document.createEvent('TouchEvent');
e.touches = [{pageX: pageX, pageY: pageY}];

Which, I think (I can’t believe it if it weren’t the case) is faster than:

e.touches = e.createTouchList(
    e.createTouch(window, target, 0, pageX, pageY, screenX, screenY)
);

Leave a Comment