-1

I want to link color to change on hover continuously, but it never works how I want it to - it won't stop on mouseleave/hover out, which you can see, in this fiddle:

  var interv;

  function changeColors(item) {
    interv = setInterval(function() {
      $(item).animate({
          color: 'red'
        }, 1000)
        .animate({
          color: 'green'
        }, 1000);
    }, 100);
  };

  $(document).ready(function() {

    $('a')
      .mouseenter(function() {
        changeColors(this);
      })
      .mouseleave(function() {
        clearInterval(interv);
        $(this).removeAttr("style");
      });


  });

Then I tried to recreate what this comment suggested, but as you can see in this fiddle, it's not working either:

    $(document).ready(function() {
  var interval;
  $('a').hover(
    function() {
      if (interval)
        clearInterval(interval);
      interval = setInterval(function() {
        $('a').animate({
            color: 'red'
          }, 1000)
          .animate({
            color: 'green'
          }, 1000);
      }, 10);
    },
    function() {
      clearInterval(interval);
      interval = null;
      $(this).removeAttr("style");
    }
  );
});
MSmS
  • 189
  • 1
  • 4
  • 15
  • uhm... your interval is 0... it's not working because you queued up thousands of animations by the time you mouse'd out. it's going to continue until it finishes all the animations you've started. An interval is the wrong tool for the job here. – Kevin B Aug 10 '17 at 20:44
  • Heck, using jquery for the animation is probably the wrong tool as well. you can get the same effect using css alone, and turn it on/off using a class. [Here's a question asking how to do the animation with css alone](https://stackoverflow.com/questions/16782498/looping-animation-of-text-color-change-using-css3), combining that with a class should be easy. – Kevin B Aug 10 '17 at 20:47

1 Answers1

0

In your CSS you will need to set transitions, these deal with your animation:

a {
  transition: all 1000ms ease-in-out;
  -webkit-transition: all 1000ms ease-in-out;
}

In the JS file you simply set the CSS via jQuery, rather than relying on .animate(), this enables you to control simple animation via CSS:

var int;

function changeColors(item, currentColor) {
    int = setInterval(function() {

        $(item).css({
            color: currentColor
        }, 1000)

        if (currentColor == 'red') {
            currentColor = 'green';
        } else {
            currentColor = 'red';
        }

    }, 1000);
};

$(document).ready(function() {

    $('a').mouseenter(function() {

        changeColors(this, 'red');

    });

    $('a').on('mouseleave', function() {

        $(this).removeAttr('style');
        clearInterval(int);

    });
});

For those who are looking at doing something similar with random colors:

Random color generator

Filthy_Rich
  • 666
  • 5
  • 20