9

I am trying to fire touch events in my JavaScript to simulate user interactions for the purpose of testing features. I have tried the following snippet:

try {
    var targetElement = document.elementFromPoint(55, 155);
    console.log(targetElement);
    var evt = document.createEvent('UIEvent');
    evt.initTouchEvent('touchstart', true, true);
    
    evt.view = window;
    evt.altKey = false;
    evt.ctrlKey = false;
    evt.shiftKey = false;
    evt.metaKey = false;
    
    targetElement.dispatchEvent(evt);
} catch (except){
    alert(except);
}

The above code throws the exception:

TypeError: Result of expression 'evt.initTouchEvent[undefined]' is not a function.

Can somebody point out what I'm doing wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
prk
  • 338
  • 1
  • 4
  • 10

2 Answers2

9

According to w3c touch spec, TouchEvent is a subclass of UIEvent. Try creating it like:

var evt = document.createEvent('TouchEvent');
vbence
  • 20,084
  • 9
  • 69
  • 118
5

change:

evt.initTouchEvent('touchstart', true, true);

to:

evt.initUIEvent('touchstart', true, true);

worked for me with nightly chrome build

Vladimir
  • 51
  • 1
  • 1