I’m trying to change background on body via JavaScript. Most of the info online use CSS :hover style transitions. What I want is doing it via JavaScript. The background-Color changes without animation, even when I have added transition. Why?
The transition is between the two “states” or selectors.
Lets say you want to transition something 2s to open 2s to close.
You would have to apply the transition to both open and close selectors.
Transitions need both a value change and a CSS selector change to work.
In the above code you haven’t changed the class or selector just the color and by using JS directly on the element you have effectively “in-lined” the color so it kind of like doing <body style = "background-color: red" >
You’ve got 3 options:
-add the transition to your change on the element e.g.
BTW, it’s probably no big deal for a 29s animation, but if your doing fast animations directly on the element its probably best to use requestAnimationFrame e.g
I just opened up your doc in Chrome and in the console pasted in that, then hit enter document.body.setAttribute("style", "background-color: blue; transition: background-color 29s ease-in")
and it turned blue after a while…
The class change wont work unless you remove: body.style.backgroundColor = isDarkmodeTime ? "black" : "white";
"inline" styles on the element have more CSS specificity than anything except !important;
Thanks for the help but the animation does not load on page load/refresh. I have to add a button listener for it to animate. Something similar to @kirupa web animation book chapter 6 where you click a button to apply js animations. I guess I can add an event listener for onLoad and add the fadeIn animation.
Check out the source on the main kirupa.com site on how dark mode is done. You’ll see a giant list of css vars at the very top. The script for loading the right set of vars runs before the rest of the page renders (just above the body element), and that ensures there is no FOUC with only a very small slowdown in rendering time since JS is running before the page can start displaying.
Transitions, Animations, and JavaScript walks through triggering CSS transitions from JavaScript, including changing style.backgroundColor and swapping classes.