Updating animation-duration in Javascript

ryantmer picture ryantmer · Jan 30, 2015 · Viewed 9.8k times · Source

After changing the animation-duration (or in this case, -webkit-animation-duration) property via JavaScript with setProperty("-webkit-animation-duration", value + "s"), I see the change in the element inspector in Chrome, but the actual animation speed doesn't change. In addition, if I manually change the value in the element inspector, there is no change either.

I've got an input field set up to take an animation speed value, which is connected to the following event listener (orbitFactor is a global var defined elsewhere):

function updateSpeed(event) {
     var planetDiv = document.getElementById(event.target.id);
     planetDiv.style.setProperty("width", event.target.value / orbitFactor);
     planetDiv.style.setProperty("height", event.target.value / orbitFactor);
     planetDiv.style.setProperty("-webkit-animation-duration", event.target.value + "s");
}

The event listener is definitely getting called, and the -webkit-animation-duration value does change in the element inspector, but the speed of the animation doesn't. Is there something I'm missing here with regards to -webkit-animation-duration? The other properties I'm changing (e.g. width and height) using the same method do change visibly.

Thanks in advance

EDIT: Note that this is a problem in Chrome 40, but it works properly in Chrome 42 and Firefox 35.

Answer

markthethomas picture markthethomas · Jan 30, 2015

Setting the style element directly using the [] to access either the vendor-prefixed or native css prop. will allow you to re-apply the animation duration property and change the rotational speed of the planet. No jquery needed. It's also worth mentioning that at the time of writing Firefox supports a non-prefixed version of the css property, while there is either mixed support or vendor-prefix support for other browsers. If considering using these animations, a given developer should seriously consider their potential user-base and probably not make this a core feature of web app. See more support info here:

http://caniuse.com/#feat=css-animation

Le code:

orbitFactor = 1e6

function updateSpeed(event) {
    var orbitDiv = document.getElementById("Mercury-orbit");
    orbitDiv.style["-webkit-animation-duration"] = event.target.value + "s";
}

function updateDiameter(event) {
    var planetDiv = document.getElementById("Mercury");
    planetDiv.style["width"] = event.target.value + "px";
    planetDiv.style["height"] = event.target.value + "px";
}

document.getElementById("orbit-period").addEventListener("change", updateSpeed);
document.getElementById("planet-diameter").addEventListener("change", updateDiameter);