1

I'm trying to get each letter color to swap from red to green and back to red.

What I have now works, but I don't like the fading, is there a better way to do this?

  const ltr = $('h1').text().split('');
  function colorChange() {
    $( 'h1' ).fadeOut(500, function() {
      redGreen();
    }).fadeIn(500).fadeOut(500, function() {
      greenRed();
    }).fadeIn(500);
  }

  setInterval( function() {
    colorChange();
  }, 1);

  function redGreen() {
    $('h1').text('');
    for(var i = 0; i < ltr.length; i++) {
      if(i % 2 == 0) {
        $('h1').append('<span class="red">' + ltr[i] + '</span>');
      } else {
        $('h1').append('<span class="green">' + ltr[i] + '</span>');
      }
    }
  }
  function greenRed() {
    $('h1').text('');
    for(var i = 0; i < ltr.length; i++) {
      if(i % 2 == 0) {
        $('h1').append('<span class="green">' + ltr[i] + '</span>');
      } else {
          $('h1').append('<span class="red">' + ltr[i] + '</span>');
      }
    }
  }
  • Why not select the elements via the "red" and "green" classes and then add and remove the alternate classes as needed? – Makaze Dec 20 '15 at 05:59

2 Answers2

0

I managed to remove the fade effect by using setTimeout.

See the plunker here

segFault
  • 3,887
  • 1
  • 19
  • 31
0

Referred to the solution for toggling class animation here : ToggleClass animate jQuery?. You should change your colorChange function to something like this :

function colorChange() {
    $( 'h1 > span' ).toggleClass( "red green", 1000, "easeInOutQuad" );
}

And make sure you build the spans at the beginning with alternative classes to each item (use one of your redGreen() or greenRed() function for the first time only).

Check this Fiddle

You need to include jQuery UI to have the effect.

Community
  • 1
  • 1