I’m trying to make a text fade in fade out transition effect as such:
let change = document.querySelector("#change")
let transition_duration = 2000
let title = ["a plane!", "Superman!", "a bird!"]
let i = 0
setInterval(async() => {
change.style.transitionDuration = (transition_duration / 2000) + 's'
change.classList.add("fadeout")
setTimeout(() => {
change.classList.remove("fadeout")
change.innerText = title[i];
i = (i + 1) % title.length
}, transition_duration / 2);
}, 3000)
#change {
padding: 0 0.5rem;
background-color: red;
border-radius: 3px;
color: white;
transition: all;
}
.fadeout {
color: transparent !important;
}
It's <span id="change">a bird!</span>
But as you can see the width does not transition when the text changes the length of the <span>
is there fix for this?
3
Answers
The animation transition needs an explicit initial and ending value.
width
needs to have an explicit value.It’s not clear how you want to animate the width. Based on your code you expect it animated when the text is changed, not ahead, so the solution.
Also you have an useless
async
.The width should be explicitly set and takes effects when you span is
display:inline-block
. To make it line up with the rest of the text you could usevertical-align:middle
(it’sbase
by default).To avoid text overflowing when width changes to bigger you need
overflow:hidden
.To get a right width with paddings you could set
box-sizing:border-box
. Also setwhite-space:nowrap
so in this case the text won’t break on a new line.To center the text during the animation place it in an inner span with
margin: 0 -100%
.To calc the next width you should set the span to
inline
and set the next title temporarily.A solution with width animation during all the transition.
Here we could actually use
async
to wait for the next animation frame. Also we cound use a css animation instead of a transition:To achieve a smooth transition effect with the changing text length, you can utilize CSS keyframe animations instead of manipulating the transition-duration property. Here’s an updated version of your code that includes the width transition: