Skip to content

Instantly share code, notes, and snippets.

@rhyzx
Last active December 18, 2015 13:59
Show Gist options
  • Save rhyzx/5794372 to your computer and use it in GitHub Desktop.
Save rhyzx/5794372 to your computer and use it in GitHub Desktop.
fast click for touch-based(mobile) browsers. require jQuery.
!function () {
if ('ontouchstart' in document) {
var touched, startX, startY
$(document)
.on('touchstart', function (evt) {
touched = evt.target
var touch = evt.originalEvent.touches[0]
startX = touch.clientX
startY = touch.clientY
})
.on('touchmove', function (evt) {
var touch = evt.originalEvent.touches[0]
if (Math.abs(startX - touch.clientX) > 10 || Math.abs(startY - touch.clientY) > 10)
touched = null
})
.on('touchend', function (evt) {
if (touched) $(touched).trigger('tap')
})
} else { // fallback for touch-unsupported browsers
$(document).on('click', function (evt) {
$(evt.target).trigger('tap')
})
}
}()
@rhyzx
Copy link
Author

rhyzx commented Jun 17, 2013

Usage

$('.element').on('tap', function () {
  // do something
})

// delegate
$('body').on('tap', '.target', function () {
  // do something
})

@rhyzx
Copy link
Author

rhyzx commented Jun 18, 2013

TODO

use native event model

var evt = document.createEvent('HTMLEvents')
evt.initEvent('tap', true, true)
target.dispatchEvent(evt)

// or CustomEvent()?

challenge

ie6 dont support custom event
http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/ hack

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