FrenkyB FrenkyB - 1 year ago 118
Android Question

Button background color on touch event is not the same as on the click event

I am trying to make button change color back to red after each click (desktop devices) or touch event (smart phones).

Here working example from codepen


$("#btnAdd").mouseenter(function () {
jQuery("#btnAdd").css("background-color", "black");
}).mouseleave(function () {
jQuery("#btnAdd").css("background-color", "#d80000");

It works fine for the click event. But, it doesnt' work for the touch event. Color stays black. How can I simulate 'mouseleave' event on the phone? It seems that only 'mouseenter' event is triggered, because color is changed to black and it stays black, until some other element is clicked.

I've also tried mousedown and mouseup events, but end result was similiar. On a desktop all fine, on smartphone color stayed black.

Answer Source

You can add both mousedown and touchstart events in your code using the on() method.

$(function() {
  $("#btnAdd").on('mousedown touchstart', function () {
    jQuery("#btnAdd").css("background-color", "black");
  }).on('mouseup touchend', function() {
    jQuery("#btnAdd").css("background-color", "red");

Here's the working example:

Aside, why don't you use CSS :active to achieve this effect?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download