CSS transition not working properly in JS? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

CSS transition not working properly in JS?

So, In this code, when you click on the red screen, it’s supposed to have ‘black’ background (as a transition). After that isn’t it supposed to go back to normal? Like... elm.... color = “blue” elem.style.transition = ‘color 0.5s’. That should make the color blue in 0.5 seconds, and back to normal in 0.5s. Isn’t that how a transition works in JS? or no? But, in this code, it changes the background color like it should, and doesn’t go back to normal. https://code.sololearn.com/WXFtc5fX5X6u/?ref=app

22nd May 2020, 7:27 AM
Ginfio
Ginfio - avatar
5 Answers
+ 9
Well, no. It isn't supposed to go back to normal without you telling it to. Transition simply specifies how long it takes to get from state 1 to state 2. In order to achieve the effects you want, you might have to do animations with keyframes. In other cases, transition on mouse hover, or pseudoelement :active might also be what you are looking for, i.e. changes back to original colour when you are not hovering across the element / element inactive. https://code.sololearn.com/WnCb7W2nS4pR/?ref=app https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_buttons_fade1 https://developer.mozilla.org/en-US/docs/Web/CSS/:active
22nd May 2020, 7:49 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
Calviղ Nice! Thanks, never knew about that. :>
22nd May 2020, 1:08 PM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Transition cannot revert the style that has been changed. If you want it to change back to red color when transition ends, you can use transitionend event. one_c.ontransitionend = () => { one_c.style.backgroundColor = 'red' }; https://code.sololearn.com/W36hek9m9F8O/?ref=app
22nd May 2020, 8:05 AM
Calviղ
Calviղ - avatar
+ 2
It can be possible to work with: function oneOnly(){ one_c.classList.toggle('two') //one_c.style.webkitTransition = 'backgroundColor 0.34s'; } }
22nd May 2020, 7:54 AM
JaScript
JaScript - avatar
+ 1
Hatsy Rei I think it’s because i mostly have done transitions on :hover, that’s probably i eas thibking that it goes back to normal._ Ok, now i know.
22nd May 2020, 7:59 AM
Ginfio
Ginfio - avatar