5

I would like to take a div and have the background fade to white on mouseenter and fade back out to black on mouseout. Any ideas on how to do this in jQuery?

user2865400
  • 151
  • 2
  • 3
  • 8

3 Answers3

10

with JQuery .hover()

  $("div" ).hover(
  function() {
     $(this).animate({backgroundColor: "#fff"}, 'slow');
  }, function() {
    $(this).animate({backgroundColor:"#000"},'slow');
  });

with JQuery .mouseover()

$("div")
  .mouseover(function() {
    $(this).animate({backgroundColor: "#fff"}, 'slow');
  })
  .mouseout(function() {
    $(this).animate({backgroundColor:"#000"},'slow');
  });

Note you have to use jquery-color (for animating colors). https://github.com/jquery/jquery-color/

Sean Francis N. Ballais
  • 2,338
  • 2
  • 24
  • 42
Sobin Augustine
  • 3,639
  • 2
  • 25
  • 43
2

You need to use either jQuery UI libarary or jQuery Colors to enable animation of colors

$('div').hover(function () {
    $(this).stop(true, true).animate({
        backgroundColor: 'black'
    })
}, function () {
     $(this).stop(true, true).animate({
        backgroundColor: 'white'
    })
})

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

OP requested jQuery. For those trying to free-hand without jQuery:

<div id="x" style="background-color:rgb(255,255,105)">hello world</div>
<script type="text/javascript">
    var unBlue=100;
    var gEvent=setInterval("toWhite();", 100);
    function toWhite(){
        if(unBlue<255) document.getElementById("x").style.backgroundColor="rgb(255,255,"+unBlue+")";
        else clearInterval(gEvent);
        unBlue+=10;
    }
</script>
gordon
  • 1,152
  • 1
  • 12
  • 18