Creating and triggering touch events in a browser with touch support?

I am trying to fire touch events in my javascript to simulate user interaction in order to test functions. I 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 an exception of 'TypeError: The result of the expression' evt.initTouchEvent [undefined] 'is not a function.'

Can someone point out what I'm doing wrong?

+8
javascript javascript-events
Apr 19 2018-11-11T00:
source share
2 answers

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

 var evt = document.createEvent('TouchEvent'); 
+9
Apr 19 '11 at 8:23
source share

changes:

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

at

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

worked for me with night chrome assembly

+5
Aug 6 2018-12-12T00:
source share



All Articles