I'm trying to keep current CSS value of an element in a variable. My problem is whenever I change style of original element, the value in variable which I've assigned before changes too.
var currentColor;
$("tr").hover(function () {
currentColor = $(this).css("background-color");
$(this).css("background-color", "#f7f7f7")
}).mouseout(function () {
$(this).css("background-color", currentColor);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr style="background-color:#FF0000"><td>Foo</td></tr>
<tr style="background-color:#00FF00"><td>Foo</td></tr>
<tr style="background-color:#0000FF"><td>Foo</td></tr>
</table>
I also tried to use .data() but it didn't solve my problem.
var currentColor;
$("tr").hover(function () {
$("div").data("currentColor", $(this).css("background-color"));
$(this).css("background-color", "#f7f7f7")
}).mouseout(function () {
$(this).css("background-color", $("div").data("currentColor"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr style="background-color:#FF0000"><td>Foo</td></tr>
<tr style="background-color:#00FF00"><td>Foo</td></tr>
<tr style="background-color:#0000FF"><td>Foo</td></tr>
</table>
UPDATE
Since community ask me why I haven't use tr:hover {background:color} I would have to include that in my actual project, and in that particular case I were into a situation that I had to modify back-ground color using jQuery. After that tr:hover {background:color} don't work and you have to manage tr:hover functionality with jQuery too.
I excluded that part from my question because I thought its not necessary to explain it.
hover? in CSS it's justtr:hover { background : #f7f7f7; }$("tr").css("background-color", "some color"), after thattr:hover { background : #f7f7f7; }don't work.