A simple, standalone library to invoke the tap event for touch-friendly web browsers.
Tappable is a simple, standalone library to invoke the tap event for touch-friendly web browsers. Currently it's only tested on iOS Mobile Safari as I don't have any other smartphones to test with. The codebase is heavily inspired by Matteo Spinelli's Remove onClick delay on webkit for iPhone and Ryan Fioravanti's Creating Fast Buttons for Mobile Web Applications.
Here's how you implement the code:
tappable('#selector', function(){
alert('tap');
});
Simple.
First, it would be wise to read the articles linked above to understand the purpose of this script. But if you're lazy, take a look at this diagram:
So, that's the tap event. But wait the minute, I can just use the touchend
event to simulate a tap, right? Wrong, because:
This means that once the finger moves, it will not fire the tap event. However, Tappable works in two special cases. First is the normal case:
When the page scrolls, the button is not tapped.
The second case is the noScroll
mode, where moving your finger on the element will not make the page scroll. This is useful for mobile web apps which might implement their own fixed headers or sections on the page.
The button is tapped when the finger is on top of the button, even after moving in and out.
tappable(selector, opts);
selector
- (string) The CSS selector expression of element to be tapped.opts
- The options object or a function.
false
) Whether or not to scroll when moving on the element.tappable-active
) A string indicating the active class applied to the element.touchstart
event is fired.touchmove
event is fired.noScroll
is true
.noScroll
is true
.touchend
event is fired.touchcancel
event is fired, or when touch moves if noScroll
is false
.false
) Whether or not to preventDefault
the click on the element.Load http://fiddle.jshell.net/cheeaun/jxwsy/show/light/ in your browser. Edit here http://jsfiddle.net/cheeaun/jxwsy/. Or scan this QR code:
Note: This is no longer needed. The latest code now does event delegation by default.
Here's a simple example:
tappable(document.body || document.getElementsByTagName('body')[0], {
onTap: function(e, target){
// e.target works too
if (target.tagName.toLowerCase() == 'a'){
alert('tap');
}
}
});
For (almost) every callback function, a second argument which is the target element node, is passed. As a bonus, the event object also have an additional target
attribute which is the target node (can be any node type, not just element node).
Feel free to fork this project! Help and feedback would be appreciated, especially if this could be tested on Android, WebOS or any other touch-friendly browsers, not just mobile ones.
Tappable is licensed under the MIT license.