I'm having trouble making my else statement work. I want to change the background color from red to blue if the background color is red, if the background color is blue I want to change it to red. I cannot see why the code below is not working, can anybody help?
$(".box").css({ "background-color": "red" }); $(".box").click(function() { if ($(".box").css({ "background-color": "red" })) { $(".box").css({ "background-color": "blue" }); } else { $(".box").css({ "background-color": "red" }); } });
.box { height: 100px; width: 100px; }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <div class="box"></div> </body> </html>
The problem is your if
condition, the .css()
method which when used in setter format returns the jQuery object which is alsways truthy that is why the else part is not executed.
If you want to compare the background-color
then you need to use the getter
version of .css()
like if($(".box").css('background-color') == 'red')
, but the value of color properties returned by the browser will depend on the browser(Some browser may return the rgb
value of the hexa value) so comparing it may not always work.
One easy solution here is to use css classes to style the elements and toggle them use toggleClass()
, in the below snippet we assigns the background color red
to the box
class, then the clicked
class overrides the color to blue
then we uses toggleClass
to add/remove the class on click of the element.
$(".box").click(function() { $(this).toggleClass("clicked"); });
.box { height: 100px; width: 100px; background-color: red; } .box.clicked { background-color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <div class="box"></div>
just check the value of css property background-color
var color = $(".box").css( "background-color" );
here is the complete code
$(".box").css({ "background-color": "red" }); $(".box").click(function() { var color = $(".box").css( "background-color" ); if ( color == "rgb(255, 0, 0)" ) { $(".box").css({ "background-color": "blue" }); } else { $(".box").css({ "background-color": "red" }); } });
.box { height: 100px; width: 100px; }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <div class="box"></div> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.