Skip to content

Instantly share code, notes, and snippets.

@morewry
Created February 28, 2015 08:50
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save morewry/538efb737ed9c4e432e4 to your computer and use it in GitHub Desktop.
Save morewry/538efb737ed9c4e432e4 to your computer and use it in GitHub Desktop.
Programmatically trigger touch event
# http://codepen.io/morewry/pen/pvLxPV
# manually create touch event
touchStartOn = (el, x = 0, y = 0) ->
try
e = document.createEvent('TouchEvent')
e.initTouchEvent("touchstart", true, true)
catch err
try
e = document.createEvent('UIEvent')
e.initUIEvent("touchstart", true, true)
catch err
e = document.createEvent('Event')
e.initEvent("touchstart", true, true)
e.targetTouches = [
pageX: x
pageY: y
]
el.dispatchEvent(e)
touchEndOn = (el, x = 0, y = 0) ->
try
e = document.createEvent('TouchEvent')
e.initTouchEvent("touchend", true, true)
catch err
try
e = document.createEvent('UIEvent')
e.initUIEvent("touchend", true, true)
catch err
e = document.createEvent('Event')
e.initEvent("touchend", true, true)
e.changedTouches = [
pageX: x
pageY: y
]
el.dispatchEvent(e)
# artificially trigger on a button
button = document.getElementById("button")
button.addEventListener "touchstart", (e) -> console.log e, "touchstart"
button.addEventListener "touchend", (e) ->> console.log e, "touchend"
touchStartOn(button, 5, 5)
touchEndOn(button, 10, 10)
@fxjs
Copy link

fxjs commented Aug 5, 2016

button.addEventListener "touchend", (e) ->> console.log e, "touchend"

changed:
button.addEventListener "touchend", (e) -> console.log e, "touchend"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment