Did you remember to check for pixels?
For instance:
css("top") == "10px"
Instead of
css("top") == "10"
Regarding the background-color
, when using .css
it returns as rgb
.
$("#red").click(function() {
var redColor = "rgb(255, 0, 0)";
var greyColor = "rgb(128, 128, 128)";
if ($(this).css("top") == "10px") {
$(this).css("top", "100px");
} else {
$(this).css("top", "10px");
}
if ($(this).css("background-color") == redColor) {
$(this).css("background-color", greyColor);
} else {
$(this).css("background-color", redColor);
}
});
#red {
position: absolute;
top: 10px;
left: 10px;
width: 100px;
height: 100px;
background-color: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<div id="red"></div>
Update
I'd suggest a different approach by using css
classes instead of inline styling.
Here's a simple example for this scenario:
$("#box").click(function() {
if ($(this).hasClass('up')) {
$(this).removeClass('up');
$(this).addClass('down');
} else {
$(this).removeClass('down');
$(this).addClass('up');
}
});
#box {
position: absolute;
width: 100px;
height: 100px;
cursor: pointer;
}
.up {
top: 10px;
left: 10px;
background-color: red;
}
.down {
top: 100px;
background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box" class="up"></div>