简体   繁体   中英

manually trigger touch event

I searched for the past 30 minutes, but didn't find a solution.

I want to trigger a touchstart event on an element.

This fires the touchstart event:

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

e.initMouseEvent("touchstart", true, true, window, 1, screenX, screenY, clientX, clientY,
    ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget);

target.dispatchEvent(e);

Note that the variables are defined by my function

But there's a problem with that. The event object doesn't have a touches property. So something like this won't work:

var touch = e.touches[0];

Is there a way to trigger a touchstart event manually (it should work on Android >= 4.0 and Chrome with touch enabled [DevTools]) ?

Please note, that I do NOT want to use any framework like jQuery. With jQuery it's easy to create a touchevent on an element ;)

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)
);

I know this has been answered, but I too struggled to find an answer to this problem and the accepted answer didn't work for me. In the end, the solution I found is really very simple and has support across browsers:

var e = new Event('touchstart');
target.dispatchEvent(e);

That's it. Couldn't be easier.

I have come up with this solution (javascript native), works for me

var el = document.getElementById('myDivId');
// desktop
el.click();

// mobile
if (window.matchMedia("(max-width: 768px)").matches) {
        // createEvent(), event.initEvent() are Depricated see Ref: [enter link description here][1]
        // var event = document.createEvent("Event"); 
        // event.initEvent("touchstart", false, true);
        // event.initEvent("touchend", false, true);
        // So the solution is:
        var event1 = new Event('touchstart');
        var event2 = new Event('touchend'); 
        el.dispatchEvent(event1); 
        el.dispatchEvent(event2);
  }

In 2019, we can use TouchEvent and Touch .

Touch is an experimental technology

For example,

const touch = new Touch({
  identifier: "123",
  target: target,
});

const touchEvent = new TouchEvent("touchstart", {
  touches: [touch],
  view: window,
  cancelable: true,
  bubbles: true,
});

target.dispatchEvent(touchEvent);

I created gist . try it simple.

我们可以这样触发:

$playBtn.bind((is_touch_device) ? 'touchstart' : 'click', playfunction);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM