Portfolio Project
An asynchronous function designed to simulate text being typed to the screen.
The typeWriter function handles dynamic element selection, input string, and a delay for the DOM element being updated.
The writeAnimation function takes an integer for the delay and is custom built for the hero-text, it adds or removes CSS classes as necessary but the idea could be expanded for integration with any element with text content.
writeAnimation(90);
// Animation function, per-string.
function typeWriter(el, str, delay) {
el.addClass("tw-bar");
// Once the recursion is done return promise => chain
return new Promise((res) => {
let increment = 0;
function nextChar() {
if (increment >= str.length) {
return res();
} else {
el.text(str.slice(0, increment + 1));
increment++;
setTimeout(() => { nextChar(); }, delay);
}
};
nextChar();
});
};
// Hero-image Title and Description Animation
async function writeAnimation(delay) {
const devTitle = "My name is ";
const devName = "David Mackie";
const devDescription = "I am a web developer";
await typeWriter($(".hero__title"), devTitle, delay);
await new Promise(res => setTimeout(res, 750) );
$(".hero__title").removeClass("tw-bar")
await typeWriter($(".hero__name"), devName, delay);
await new Promise(res => setTimeout(res, 750) );
$(".hero__name").removeClass("tw-bar")
await typeWriter($(".hero__excerpt--small"), devDescription, delay);
};