On my website I have a part for showing some data. This is hooked up to a button to load other data when pressed. The elements stay the same, but the text inside the spans is changed to show the data. I’ve noticed that just changing the texts and numbers looks a little boring, so I was looking for something like an animation for changing the text. Something like the CSS transition argument, but for changing text. From my own research I did not find anything suiting my needs, maybe one of you has some code to share. I have in mind something like the text going away to the side with the new text coming in from the other side. Hard to explain what I mean, without having something to show.
Here is a rough example of how I currently replace the text with jquery:
$("#span-1").text("new text");
I tried creating a new class, giving it the transition property and on text change, change the class of the element, then change the text and change back the class after a timeout for the transition, but the text still changed immediatly.
CSS:
.text {
transition: all 1s ease;
/* other properties */
}
.text-transition {
transition: all 1s ease;
}
JS:
$("#span-1").text("New Text");
$("#span-1").removeClass("text");
$("#span-1").addClass("text-transition");
setTimeout(() => {
$("#span-1").removeClass("text-transition");
$("#span-1").addClass("text");
}, 1000);
This is roughly what I tried, I also tried switching around the orders a bit, you get the idea.
2
Answers
Still not 100% sure what you’re looking for, but here’s one approach:
In this example I have static text and the class transition is loaded on hover, but you can update it so that when the data is loaded you could set the text of the
.new-text
div
to that loaded data, and then you could update theleft
value directly or add a class that has that info. Alternatively you could add another wrapper div around theoriginal-text
andnew-text
divs and set the left transition on that wrapper instead oforiginal-text
andnew-text
divs, so that you only need to update class for one element (with the downside being that the DOM has an extra element.)Let me know if this is what you had in mind, or if there are adjustments you were looking at.
const texts = ["Old Text", "First New Text", "Second New Text", "Third New Text"];
.let currentIndex = 0;
.fade-out
class.span.textContent = texts[currentIndex];
.currentIndex = (currentIndex + 1) % texts.length;
.fade-out
class.