2

i'm not sure what is wrong with this script but it just doesn't seem to want to work. What is meant to happen is that the box should fade the color in and out according to mouseenter/leave.

$(document).ready(function() {
    $('.square-box').mouseenter(function() {
        $(this).animate({
            background-color: '#AAAAAA'
        }, 1000);
    });
    $('.square-box').mouseleave(function() {
        $(this).animate({
            background-color: '#CCCCCC'
        }, 1000);
    });
});

https://jsfiddle.net/k9met5oz/

What am i doing wrong? Thanks.

FoxyFish
  • 874
  • 1
  • 12
  • 21

3 Answers3

4

You can animate only attributes with numeric values. But you can use this plugin https://github.com/jquery/jquery-color/ for color animation. Try this:

$(document).ready(function() {
    $('.square-box').mouseenter(function() {
        $(this).animate({
            "backgroundColor": '#AAAAAA'
        }, 1000);
    });
    $('.square-box').mouseleave(function() {
        $(this).animate({
            "backgroundColor": '#CCCCCC'
        }, 1000);
    });
});
.square-box {
  width: 200px;
  height: 200px;
  line-height: 200px;
  cursor: pointer;
  background-color: #CCC;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.js"></script>

<div class="square-box">TEST BOX</div>
bhansa
  • 7,282
  • 3
  • 30
  • 55
Andriy Lozynskiy
  • 2,444
  • 2
  • 17
  • 35
  • 1
    I accepted this as the answer as it does work, however i found out that jquery ui has color animate, i just need to include the ui (or this plugin in your example). – FoxyFish Sep 24 '17 at 14:18
3

Seems like you cannot animate colors by default in jquery

You can do it with changing css properties.

$(document).ready(function() {
  $('.square-box').mouseenter(function() {
    $(this).css({
      "background-color": "#aaa"
    });
  }).mouseleave(function() {
    $(this).css({
      'background-color': '#CCCCCC'
    })
  });
});
.square-box {
  width: 200px;
  height: 200px;
  line-height: 200px;
  cursor: pointer;
  background-color: #CCC;
  text-align: center;
  transition: 1s all;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class='square-box'>
  TEST BOX
</div>
bhansa
  • 7,282
  • 3
  • 30
  • 55
0

Jquery cannot animate colors by default. But you don't need a plugin. You can do this with CSS transitions much more easily:

.square-box {
  width: 200px;
  height: 200px;
  line-height: 200px;
  cursor: pointer;
  background-color: #CCC;
  text-align: center;
  -webkit-transition:background 1s;
-moz-transition:background 1s;
-o-transition:background 1s;
transition:background 1s
}

.square-box:hover {background:#AAAAAA}
<div class='square-box'>
  TEST BOX
</div>
Adam Love
  • 646
  • 6
  • 8