0

I can't make this script to work. I searched online and I can't find any good answer.

$( document ).ready(function() {

$("#container").click(function(){
    var color = $(this).css("background");
    if(color == "#ffffff"){
        $(this).css("background", "#e1e1e1");
    }
    else {
        $(this).css("background", "#ffffff");
    }

});

});

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="css/stylesheet.css" type="text/css" />
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/script.js" type="text/javascript"></script>
<title>Document sans nom</title>
</head>

<body>

<div id="container">

    <a href="#" class="a">Start</a>

</div>

</body>

</html>
1
  • 1
    Can you also share your HTML or recreate your page on jsFiddle? Commented Feb 25, 2014 at 12:42

2 Answers 2

3

Because .css('background') may not return the color in the format you assume it is returning, based on browser it may return a hexa, rgb or rgba format

$(document).ready(function () {
    $("#container").click(function () {
        $(this).css("background-color", function () {
            var color = $(this).data("background") == '#e1e1e1' ? '#ffffff' : '#e1e1e1';
            $(this).data('background', color);
            return color;
        });
    });
});

Demo: Fiddle


But a far more easier solution is to use toggleClass() like

#container {
    background-color: #ffffff;
}
#container.toggled {
    background-color: #e1e1e1;
}

then

$(document).ready(function () {
    $("#container").click(function () {
        $(this).toggleClass('toggled');
    });
});

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

@David if this answers your question, you should accept this answer as the correct one, by clicking the checkmark next to it.
0

You need to use .css("background-color"); but this will return as a rgb not hex so you would need to modify your code slightly.

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.