Questionnaire
Questionnaire

Reputation: 674

Changing CSS keyframes through Javascript

I would like to know whether it is possible to adjust the contents of CSS keyframes, as I have seen a variety of suggestions online but none of them seem to work for me.

These are the keyframes I have:

@keyframes changeColor {
  0% {
    color: yellow;
  }
  50% {
    color: red;
  }
}

@-moz-keyframes changeColor {
  0% {
    color: yellow;
  }
  50% {
    color: red;
  }
}

@-webkit-keyframes changeColor {
  0% {
    color: yellow;
  }
  50% {
    color: red;
  }
}


@-o-keyframes changeColor {
  0%{
    color: yellow;
  }
  50% {
    color: red;
  }
}

I would like to be able to adjust the color attribute for each one of the above keyframes through Javascript, so that the colours can be changed according to the value passed through Javascript. Is this possible in any way?

Thank you

Upvotes: 2

Views: 3263

Answers (2)

rpivovar
rpivovar

Reputation: 3448

This might work better entirely in Javascript, with the only consistent CSS attribute that should always be on the element a transition attribute: transition: color 0.5s ease-out for example.

Then in javascript you could have a setInterval alternate between colors somehow:

// Note that this is psuedocode and will need to be refactored slightly to better fit your own code

// variables storing color values
var colorA = 'red', 
    colorB = 'blue';

//store element you are changing in a variable
const ELEMENT = document.querySelector('element'); 

function changeColors() {

    // store current color value of ELEMENT in a variable called currentColor
    let currentColor = ELEMENT.style.color; 

    // if color is currently A, switch to B
    if (currentColor == colorA) { 
        ELEMENT.style.color = colorB;
    }
    // else, switch to A
    else { 
        ELEMENT.style.color = colorA;
    }

}

// call set interval to alternate colors with same timing value as set in transition attribute in CSS
setInterval(changeColors, 500); 

That's just one way it could be done in javascript, but the main takeaway here is that, at the end of the day, it's probably a lot more feasible to do it all in javascript rather than with CSS animations.

Upvotes: 1

davecar21
davecar21

Reputation: 2674

Animating KeyFrame using jQuery is possbile using jQuery.Keyframes

var supportedFlag = $.keyframe.isSupported();
$.keyframe.define([{
    name: 'roll-clockwise',
    '0%': {
        'color' : 'green'
    },
    '100%': {
        'color' : 'yellow'
    }
    }
]);

$("p").playKeyframe({
    name: 'changeColor',
    duration: 2000
});

For more info please see this link. https://github.com/Keyframes/jQuery.Keyframes

Upvotes: 1

Related Questions