2

I want to make box which will change background-color with animation after hover on it but my jQuery script doesn't make any effect on div. However there are no errors.

$(document).ready(function(){
    $("#box").hover(function () {
    $(this).stop().animate({ backgroundColor: "#F00" },700)
    }, function() {
    $(this).stop().animate({ backgroundColor: "#AAA" },700)}   
);
}); 
<div id="box" style="display:block; width: 500px; height: 100px; margin: 0 auto; background-color:red;"></div>
Roberto
  • 315
  • 1
  • 5
  • 18
  • 1
    You can't animate background color with jquery it self... you will need JQuery UI, or some plugin, like this: http://www.bitstorm.org/jquery/color-animation/, or, you could use css: https://www.tjvantoll.com/2012/02/20/css3-color-animations/ – sinisake May 18 '16 at 23:16
  • Ahh ok, Thank You :) – Roberto May 18 '16 at 23:21

4 Answers4

0

Background-color is not a property that you can animate with jQuery. Instead, you can either use the CSS :hover pseudoelement, or you can change the background color without animate.

CSS

#box {
    background-color: red;
}
#box:hover {
    background-color: #F00;
}

jQuery

$(this).css({'background-color' : 'red'});
Schiem
  • 589
  • 3
  • 12
0

You can use the Color animation jQuery-plugin to animate the background color.It's very simple, here's a complete example:

  <head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#box").hover(function () {
                $('#box').animate({ backgroundColor: 'black' })
            }, function () {
                $('#box').animate({ backgroundColor: 'red' })
            }
        );
        });
    </script>
</head>
<body>
    <div id="box" style="display: block; width: 500px; height: 100px; margin: 0 auto; background-color: red;"></div>
</body>
Denys Wessels
  • 16,829
  • 14
  • 80
  • 120
0

You don't need to write JavaScript or Jquery for this effect. You can use CSS3. Code is as under :-

<!-- HTML-->
<div class="box"></div>

/* CSS */

.box {
  width: 150px;
  height: 150px;
  background: red;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  -webkit-transition: background-color 2s ease-out;
  -moz-transition: background-color 2s ease-out;
  -o-transition: background-color 2s ease-out;
  transition: background-color 2s ease-out;
  }

  .box:hover {
  background-color: green;
  cursor: pointer;
  }

Check on JSFiddle

Anand Deep Singh
  • 2,560
  • 3
  • 22
  • 28
0

you should import a little more jquery functions for animate backgroundColor. this link is very helpful for you.

Community
  • 1
  • 1