Typewriter effect
The following code implements a typewriter effect for headings inside my blog. I took extra steps to ensure that the typing starts from the very beginning of the title - there is a slight delay to ensure the elements become visible first, there is a phantom element that ensures there are no jumps and stutters in spacing as the text is being manipulated, and the opacity is managed timely to ensure a proper visual presentation.
HTML:
JAVASCRIPT: document.addEventListener('DOMContentLoaded', function() { const subString = 'developmentlog'; const getURL = window.location.href; if (getURL.includes(subString)) { const headings = document.querySelectorAll('h1, h2, h3, h4'); if (headings.length > 0) { headings.forEach((heading, index) => { const typedText = heading.innerText; let i = 0; const placeholder = document.createElement('span'); placeholder.innerText = typedText; placeholder.style.visibility = 'hidden'; heading.innerHTML = ''; heading.appendChild(placeholder); function typeWriter() { placeholder.style.display = 'none'; heading.style.opacity = '1'; if (i < typedText.length) { heading.innerHTML += typedText.charAt(i); i++; setTimeout(typeWriter, 70 + (index * 50)); } } setTimeout(typeWriter, 800); }); } } });
CSS:
COMMENTS:
Leave a comment: