Reputation:
I have an html button that when the user clicks the button it will change color from blue to red and back. Is there a better way to do this in jQuery?
clicked = true;
$(document).ready(function() {
$("button").click(function() {
if (clicked) {
$(this).css('background-color', 'red');
clicked = false;
} else {
$(this).css('background-color', 'blue');
clicked = true;
}
});
});
button {
background-color: blue;
height: 100px;
width: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Press</button>
Upvotes: 0
Views: 185
Reputation: 3088
you can use toggle class function for that like this
clicked = true;
$(document).ready(function(){
$("button").click(function(){
$(this).toggleClass('red');
$(this).toggleClass('blue');
});
});
button{
height:100px;
width:150px;
}
.red
{
background-color:red;
}
.blue
{
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Button Fun</title>
<script src = 'bower_components/jquery/dist/jquery.js'></script>
<script type="home.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css"/>
</head>
<body>
<button class="blue">Press</button>
</body>
</html>
Upvotes: 0
Reputation: 298
Using jquery and toggleClass:
$("button").click(function(){
$('.btn').toggleClass('toggled');
})
.btn{
background-color: blue;
padding: 10px;
color: white;
}
.toggled{
background-color: red;
}
<button type="button" class="btn">Press</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 21575
One way you could do this is add a class for the red background color and toggle that class:
$("button").click(function(){
$(this).toggleClass("redButton");
});
button{
background-color: blue;
height:100px;
width:150px;
}
.redButton { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Press</button>
Upvotes: 1