Tommy K
Tommy K

Reputation: 1807

change color of button when clicked

I have a button with a background linear-gradient in css, but I want to inverse the gradient when the button is clicked. Here's the thing, I mean click as in "depressed" like when you have the mouse over the button and have the mouse button pressed, but when you let go of the mouse button, I want it to go back to normal. When I try to search this I get a bunch of answers on permanently changing a button after its been clicked, however I only want to change the button's background color while its being clicked. How would I go about this?

Upvotes: 1

Views: 582

Answers (4)

Bitwise Creative
Bitwise Creative

Reputation: 4105

You can use addClass and removeClass on events mousedown and mouseup.

$(function() {
    $('button').on('mousedown', function() {
        $(this).addClass('down');
    });
    $('button').on('mouseup', function() {
        $(this).removeClass('down');
    });
});
button {
  background: -webkit-linear-gradient(red, orange); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(red, orange); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(red, orange); /* For Firefox 3.6 to 15 */
  background: linear-gradient(red, orange); /* Standard syntax */
}
button.down {
  background: -webkit-linear-gradient(orange, red); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(orange, red); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(orange, red); /* For Firefox 3.6 to 15 */
  background: linear-gradient(orange, red); /* Standard syntax */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Gradient Reverse on Click</button>

:active is much cleaner, but sometimes it seems to get stuck with focus. I can't seem to reproduce that issue currently, so maybe it's something of the past...

Upvotes: 0

Federico
Federico

Reputation: 1251

Hi here is how you do it in CSS:

button:active{
    background-color:red;
}

here in JS:

<button type="button"
    onmousedown="this.style.backgroundColor='red'"
    onmouseup="this.style.backgroundColor=''"
>CLICK ME</button>

Upvotes: 0

void
void

Reputation: 36703

button:active {
    // Background color code for inverse gradient
}

Upvotes: 0

js_
js_

Reputation: 185

You probably want to use :active pseudo class.

button:active {
    background: red;
}

See this example: http://jsfiddle.net/1jnb8yd6/

Upvotes: 1

Related Questions