Reputation: 109
so I'm currently making a toplist and I'd like to add a little javascript to it. I've decided to make a background color fade in when a visitor hovers their mouse over a name.
But the problem is, it keeps flashing in and out, which is quite annoying! - Here is my code:
<script type="text/javascript">
var isOn = false;
if(isOn == false)
{
$('#rank<?= $info['ID']; ?>').hover(function(){
isOn = true;
$('#rank<?= $info['ID']; ?>').animate({
backgroundColor: '#FF0000'
});
});
}
$('#rank<?= $info['ID']; ?>').mouseout(function(){
isOn = false;
$('#rank<?= $info['ID']; ?>').animate({
backgroundColor: 'white'
});
});
</script>
I want to fade in to a color when a visitor hovers over the area, and change back to a different color when a visitor hovers out of the area.
Thank you.
Upvotes: 1
Views: 341
Reputation: 6908
You cannot animate colors using standard jQuery, you need additional scripts, EG: jQuery UI.
Also searching should have helped to fix this problem: https://stackoverflow.com/a/2302005/2373138
Upvotes: 2
Reputation: 10675
The problem is that you are using the hover
shortcut incorrectly. hover
actually takes two functions and binds to mouseenter
and mouseleave
. Your current code is binding to mouseenter
and mouseout
, which will cause problems.
What you actually want is this:
var isOn = false;
if(isOn == false)
{
$('#rank<?= $info['ID']; ?>').hover(function() {
isOn = true;
$('#rank<?= $info['ID']; ?>').animate({
backgroundColor: '#FF0000'
});
},
function() {
isOn = false;
$('#rank<?= $info['ID']; ?>').animate({
backgroundColor: 'white'
});
});
}
You might also want to include some .stop()
functions so you don't have a problem with your animation queue.
You should never use mouseover
or mouseout
because they fire multiple times when you enter or leave an element. See the demo at the bottom of http://api.jquery.com/mouseenter/ for an illustrative example.
Upvotes: 3
Reputation: 9151
Use CSS(3) check here
If you want to use JS, use a mouse-enter and -leave start/stop function.
Upvotes: 1
Reputation: 1
You must use the latest Jquery color plugin.
From api.jquery.com/animate/
...most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used).
Upvotes: 0