I'd like to be able to mimic the behavior of the :active
pseudo class on all elements in Android webkit. Currently, the :active
syntax only works on a
elements (links). Nearly all of the actionable elements in the app I'm working on are something other than a standard link tag. iOS webkit supports :active
on all elements.
/* works on both android iOS webkit */
a:active {
color: blue;
}
/* works on iOS webkit, does not work on android webkit */
div:active {
color: red;
}
I've found a couple of resources [1,2] that solve similar problems, but they're both a bit heavy, and I'm wondering if there's a lighter weight solution that I'm just not able to find.
:active can also apply to any element. In the Pen below, clicking anywhere on the page will make the whole page yellow: HTML.
The :active CSS pseudo-class represents an element (such as a button) that is being activated by the user. When using a mouse, "activation" typically starts when the user presses down the primary mouse button.
A link becomes active when you click on it. Tip: The :active selector can be used on all elements, not only links. Tip: Use the :link selector to style links to unvisited pages, the :visited selector to style links to visited pages, and the :hover selector to style links when you mouse over them.
How do I keep an active CSS style after clicking an element? The :active selector is used to select and style the active link. A link becomes active when you click on it. The :active selector can be used on all elements, not only links.
Based on what @caffein said, here's a full implementation of this:
For all :active code, write CSS rules that look like this.
my-button:active, .my-button.fake-active {
background-color: blue;
}
Then in your document ready event add this code:
if (navigator.userAgent.toLowerCase().indexOf("android") > -1) {
$(".my-button")
.bind("touchstart", function () {
$(this).addClass("fake-active");
})
.bind("touchend", function() {
$(this).removeClass("fake-active");
});
}
This has the advantage of using the fast native :active class on iOS, and dropping back to JavaScript on Android.
Taken from my blog at http://pervasivecode.blogspot.com/2011/11/android-phonegap-active-css-pseudo.html
EDIT: I've since discovered that buttons can occasionally 'stick' in the fake-active state. The fix for this is to also handle the touchcancel event. E.g. add this to the above..
.bind("touchcancel",
function() {
var $this = $(this);
$this.removeClass("fake-active");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With