Reputation: 225
I have a button and i want to change its background color to white on click, and then when i click another time it return back to its original background color, how can i do that? here is my code:
$(document).ready(function () {
$("button").click(function () {
$(this).css("background-color", "#FFF");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Hello</button>
Upvotes: 1
Views: 15411
Reputation: 15555
$(document).ready(function() {
$("button").click(function() {
$(this).toggleClass("new");
});
});
.new {
background-color: red
}
button {
background-color: white
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Hello</button>
Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
Upvotes: 2
Reputation: 4536
All you need to do is add some sort of toggle boolean, in this example it's the var named 'white'.
var white = false
var bgcolor;
$(document).ready(function () {
$("button").click(function () {
if (white = !white) {
bgcolor = $(this).css('backgroundColor');
$(this).css("background-color", "#FFF");
} else {
$(this).css("background-color", bgcolor);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Hello</button>
Upvotes: 3
Reputation: 285
Record the initial button color, then set/reset based upon state flag
$(function(){
var buttoncolor = $('button').css('background-color');
var state=true;
$('button').click(function(){
if (state )
{
$('button').css('background-color','white');
}
else
{
$('button').css('background-color', buttoncolor );
}
state=!state;
})
});
Upvotes: 1
Reputation: 2052
Try this, simple JS solution;
$(document).ready(function () {
var i=0;
$("button").click(function () {
if(i==0){
$(this).css("background-color", "#FFF");
i=1;
}
else{
$(this).css("background-color", "#000");
i=0;
}
});
});
Upvotes: 1
Reputation: 337560
The easiest way to do this would be to set the background-color
using a CSS class, then call toggleClass()
in the click event handler, something like this:
$("button").click(function() {
$(this).toggleClass('foo');
});
button {
background-color: #000;
color: #FFF;
}
button.foo {
background-color: #FFF;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Hello</button>
Upvotes: 5