AngularJS Directive for Google FastButton

On December 27, 2012, in Javascript, by Anuj Gakhar

In my latest project, I’ve been working on a HTML5 Mobile App for iPad and one of the things we wanted to get rid of was the 300ms click delay that Mobile Safari has. There is a reason for the delay to be there in first place, i.e. the browser is waiting to see whether it’s a tap or a double tap. And since we were not implementing double taps in our application, it made sense to get rid of the 300ms delay and improve the user experience.

There is an excellent article by Google on this subject. If you read that article in full, you will understand the concept clearly and how to avoid the 300ms delay and cover all edge case scenarios as well. Luckily, someone has also ported this Javascript code into a nice little jQuery plugin.

However, since I was using AngularJS for my project, I wanted to set this up as an AngularJS Directive and not just a jQuery plugin. I wanted to replace all the ng-click‘s with my own directive and call it “fast-click”.

With the code from Google and the jQuery plugin from Alex Black, this task was a piece of cake. Here is the code for the directive.

angular.module('fastClick', []).directive('fastClick', function() {
    return function(scope, elem, attr) {
        elem.fastClick(function (e) {
            scope.$apply(attr.fastClick);
        })
    };
});

This is assuming you have AngularJS and the jQuery plugin both loaded on the page before this code runs. I won’t be showing that part of the code here as there are several ways of doing that and is pretty straightforward. Anyways, once this directive is in place, you can now call the fastClick directive anywhere in your partials/views. e.g.

<button fast-click="doSomething()">I am a button</button>

Notice how the directive is called “fastClick” and on the button code, we use “fast-click”. This is nothing wrong, this is how it’s supposed to be. You can read more about the implementation here.

Since I am pretty new to AngularJS, if there is a better way of doing this, please let me know.

Tagged with:  

5 Responses to AngularJS Directive for Google FastButton

  1. Bema says:

    This is pretty useful, thanks for sharing Anuj.

  2. Any chance you could put up a working demo or example? This is exactly what I need and I can’t seem to get it working.

Leave a Reply

© 2011 Anuj Gakhar
%d bloggers like this: