Wednesday, 16 November 2011

Android Phonegap :active CSS pseudo class doesn't work. A workaround..

If you're building a cross-platform Phonegap app, you may well run in to the issue that your CSS :active pseudo-classes simply don't work when running on Android. They may work on your a (link) elements, but not on div or others.

Luckily there's a simple workaround. This workaround will continue using the fast, native, JavaScript-free :active class on iOS, and drops back to using the JavaScript on Android.

  • First, in your CSS, find every instance of the :active class. Add another rule that maps a class called fake-active to the same style.
E.g.

.my-button:active {
 background-color: blue;
}

Becomes:

my-button:active, .my-button.fake-active {
 background-color: blue;
}
  • Now, in your document ready event, when running on Android only, attach event handlers for touchstart and touchend to all the classes that have used :active. Make these add and remove the fake-active class.
if (navigator.userAgent.toLowerCase().indexOf("android") > -1) {
    $(".my-button")
    .bind("touchstart", function () {
        $(this).addClass("fake-active");
    })
   .bind("touchend", function() {
        $(this).removeClass("fake-active");
    });
    .bind("touchcancel", function() {
        // sometimes Android fires a touchcancel event rather than a touchend. Handle this too.
        $(this).removeClass("fake-active");
    });
}

Note that you can use the $(".my-button, .my-other-element, .even-more-elements") jQuery syntax to bind the events to other classes too.

3 comments:

  1. Thanks for this article - but FWIW it doesn't appear to be working for me in Android as I get the "stuck" issue even w/your touchcancel update.

    My app touch events all happen on touchstart - is that possibly why Android is never removing the "fake-active" class? I've used your script verbatim btw.

    ReplyDelete
  2. .bind("touchend", function() {
    $(this).removeClass("fake-active");
    }); <---- That semicolon sucks ;)

    ReplyDelete