I have previously asked a question about triggering a CSS transition with JavaScript & setTimeout
(JavaScript: Trigger CSS Transition with window.setTimeout). This question is trying to get more information on that.
I have a function which changes the content and fades in a paragrapn p#test
:
function test() {
var done=false;
var p=document.querySelector('p#test');
window.setInterval(doit,4000);
var data=0;
function doit() {
p.removeAttribute('on'); // 1
p.offsetHeight; // 2 force update
p.innerHTML=data++; // 3
p.setAttribute('on',null); // 4
}
}
The CSS is:
p#test {
opacity: 0;
}
p#test[on] {
transition: opacity 1s;
opacity: 1;
}
I note that the transition
property must be set in the p#test[on]
rule. If set for the p#test
rule, it will not work.
I find that steps 2
& 3
above can be interchanged.
However, I cannot get it working at all if I try to set the properties in JavaScript alone:
function doit() { // DOES NOT WORK
p.style.opacity=0;
p.offsetHeight;
p.innerHTML=data++;
p.style.opacity=1;
}
So I conclude:
- Changing an attribute (or class) in JavaScript will trigger a CSS transition
- Changing a CSS property in JavaScript will not trigger a transition
- The transition will only be triggered if the
transition
property in in the triggered rule.
Sorry about the long preamble. The question is:
Precisely what JavaScript will actually trigger a CSS transition? Is it only a change of class or attribute, or will anything else work?
I have added a Fiddle here: https://jsfiddle.net/comparity/a7qt297m/