diff --git a/README.md b/README.md index de3f2a06..e8085d96 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ For Ruby, there's a third-party gem called [fastclick-rails](http://rubygems.org ### Ignore certain elements with `needsclick` ### Sometimes you need FastClick to ignore certain elements. You can do this easily by adding the `needsclick` class. + ```html Ignored by FastClick ``` @@ -123,6 +124,24 @@ Another example of when to use the `needsclick` class is with dropdowns in Twitt Dropdown ``` +### Whitelisting ### + +If you'd rather opt-in to using FastClick instead of opting out with the `.needsclick` class, you can specify a CSS selector that elements must match in order to make use of FastClick's magic. For example: + +```js +FastClick.attach(document.body, { + // only enable for elements with the .fastlcick class and their children + selector: '.fastclick, .fastclick *' +}); +``` + +```html +Ignored by FastClick +Uses FastClick +``` + +**Warning**: This does not work on all browser versions generally supported by FastClick. If you need to support devices that don't support [`element.matches()` or `element.matchesSelector()`](http://caniuse.com/#search=matches) (e.g., Android 2.1 and below, iOS 3 and below, etc.), you should **not rely on this functionality**. If a selector is specified for an unsupported browser, FastClick will disregard the selector and perform the default FastClick behavior. + ## Examples ## FastClick is designed to cope with many different browser oddities. Here are some examples to illustrate this: diff --git a/lib/fastclick.js b/lib/fastclick.js index 3af4f9d6..5bf30311 100644 --- a/lib/fastclick.js +++ b/lib/fastclick.js @@ -102,6 +102,14 @@ */ this.tapTimeout = options.tapTimeout || 700; + /** + * To whitelist specific elements, a selector string can be specified that will + * limit the elements on which FastClick works. + * + * @type {string} + */ + this.selector = options.selector || ''; + if (FastClick.notNeeded(layer)) { return; } @@ -225,6 +233,18 @@ * @returns {boolean} Returns true if the element needs a native click */ FastClick.prototype.needsClick = function(target) { + + // Require a click for all that don't match this.selector, if specified + if (this.selector) { + var fnMatches = target.matches || target.matchesSelector || target.webkitMatchesSelector || target.mozMatchesSelector || target.msMatchesSelector || null; + + if (!fnMatches) { + console.error('Unsupported browser for whitelisting with Fastclick. Ignoring selector.') + } else if (!fnMatches.call(target, this.selector)) { + return true; + } + } + switch (target.nodeName.toLowerCase()) { // Don't send a synthetic click to disabled inputs (issue #62)