Skip to content

Instantly share code, notes, and snippets.

@JHBaik
Forked from morewry/dispatch-touch-event.coffee
Created December 21, 2018 03:03
Show Gist options
  • Select an option

  • Save JHBaik/f49cff927e4bce7061db76f369db238d to your computer and use it in GitHub Desktop.

Select an option

Save JHBaik/f49cff927e4bce7061db76f369db238d to your computer and use it in GitHub Desktop.

Revisions

  1. @morewry morewry created this gist Feb 28, 2015.
    45 changes: 45 additions & 0 deletions dispatch-touch-event.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    # 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)