Reputation: 1496
What I aim is that if when hovered, and if the cell is already active, the hovered TD will be black (for deactivation), and orange for if it's still inactive (for activation).
But with my code, every time I hover it on td, the color won't return on its previous background color. (Still orange or black even the mouse leaves) What event should I be using?
$("td").hover(function(){
var cell = $(this).html();
if(cell == "")
$(this).css( "background-color", "orange");
else
$(this).css( "background-color", "black");
});
Upvotes: 0
Views: 80
Reputation: 1391
Hover uses a handler in and handler out. 2 functions separated by comma hover()
I would use classes for the highlighting
.orange {
background: none no-repeat 0 0 orange;
}
.black{
background: none no-repeat 0 0 black;
}
Then use addClass and removeClass
$("td").hover(
function(){
var cell = $(this).html();
if(cell == "") {
$(this).addClass("orange");
} else {
$(this).addClass("black");
}
},
function () {
$(this).removeClass("orange").removeClass("black");
}
});
Upvotes: 1
Reputation: 6149
What happens is when you call $(this).css( "background-color", "orange");
or similar you are changing the CSS and it'll stay that way until you ask to change it again.
When you only pass hover
a single argument, it runs that same argument when you both enter, and leave, however if you pass a second argument in, then the first will be called for enter, the second for leave.
$("td").hover(function(){
//Put original code here
}, function(){
$(this).css( "background-color", /* Whatever the original color was */);
});
Upvotes: 0
Reputation: 33870
.hover()
is a great function for toggling, but in you case, you are better by spliting the mouse leave and enter :
$('td').on({
mouseenter : function(){
var cell = $(this).html();
if(cell.length===0)
$(this).css( "background-color", "orange");
else
$(this).css( "background-color", "black");
},
mouseleave : function(){
$(this).css('background-color', '');
}
})
Upvotes: 0
Reputation: 4873
Try creating and toggling a class, this will help you return to default state.
<Style>
.active {background-color:black;}
.inactive {background-color:orange;}
</style>
<script>
$("td").hover(function(){
var cell = $(this).html();
if(cell == ""){
$(this).toggleClass("active");
}
else{
$(this).toggleClass("inactive");
}
});
Upvotes: 0
Reputation: 3101
Instead of checking the empty value it's better to check the length of the content
$("td").hover(function(){
var cell = $(this).html();
if(cell.length===0)
$(this).css( "background-color", "orange");
else
$(this).css( "background-color", "black");
});
Upvotes: 1