I wanted to add just a bit of whimsy to a recent project so I made the user feedback from an AJAX call get typed out instead of simply fading in. You can use the jQuery function below by calling it with a selector and a message as the second parameter. It will clear the selector of any previous text and then type the response it then fade it out over a few seconds.
function typeAndFade(selector, newText, typingSpeed = 50, fadeDuration = 5000) {
const $el = $(selector);
$el.empty(); // Clear existing content
let i = 0;
const interval = setInterval(() => {
$el.append(newText.charAt(i));
i++;
if (i >= newText.length) {
clearInterval(interval);
// Wait a moment, then fade out
setTimeout(() => {
$el.fadeOut(fadeDuration);
}, 800); // small delay before fade
}
}, typingSpeed);
}
typeAndFade('#selector', 'Message');