6

I'm trying to change the background color of an link when the user touches/taps on a mobile, although the following code works, sometimes the link remains black and doesn't change back to white when you release, is there a better way of coding it?

$('#test').bind('touchstart', function() {
    $(this).css('background-color', 'black');
});

$('#test').bind('touchend', function() {
    $(this).css('background-color', 'white');
});​

Thanks!

user1937021
  • 10,151
  • 22
  • 81
  • 143

1 Answers1

11

This can be done in CSS without jQuery:

a:active
{
    background-color: black;
}

Note about compatibility with the Android's stock browser

For some reason, the code above does not work in the Android's stock browser (and maybe some other browsers). However it will work once you add the ontouchstart="" argument to the <body> tag like so:

<body ontouchstart="">

Also, the Android stock browser highlights the links by default (with blue background, on my phone). To disable this, type:

a
{
    -webkit-tap-highlight-color: rgba(255, 255, 255, 0); 
}

See this and this for more details.

Jsfiddle here

Community
  • 1
  • 1
Petr R.
  • 1,247
  • 2
  • 22
  • 30