Thelostcause
Thelostcause

Reputation: 113

Displaying Char by Char in HTML using JavaScript and then removing it with new word

I wanted to do something like this done in a Portfolio

Check this out

sabbircs06.github.io/portfolio/

In the Introduction Section, It's displaying Developer. Which is displaying char by char after 1sec and then selecting the displayed word, removing it and showing next string char by char.

I am having very hard time to code this in Vanilla Js. Kindly someone help me on that, I am ok if you use jquery for this, but Vanila js will be preferrable.

Upvotes: 0

Views: 68

Answers (1)

Will
Will

Reputation: 3241

It takes a little bit of recursion, sprinkle in some timers and fiddling with some classes, but this is a pretty close approximation.

let words = ["Dog", "Cat", "Parakeet", "Ferret"];

window.addEventListener("DOMContentLoaded", () =>
  displayWord(document.querySelector("#adjective"))
);

function displayWord(el) {
  el.classList.remove("selected");
  const word = words.shift();
  words.push(word);
  displayLetters(el, word);
}

function displayLetters(el, word, idx = -1) {
  idx++;
  if (idx > word.length) {
    setTimeout(() => el.classList.add("selected"), 1250);
    return setTimeout(() => displayWord(el), 2000);
  }
  el.innerHTML = word.slice(0, idx);
  setTimeout(() => displayLetters(el, word, idx), 200);
}
p {
  font-size: larger;
}

#adjective {
  font-style: italic;
}

.selected {
  background-color: rgb(180, 215, 255);
}

#caret {
  animation: blink-animation 1s steps(5, start) infinite;
}

@keyframes blink-animation {
  to {
    visibility: hidden;
  }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<p>I am a <span id="adjective"></span><span id="caret">|</span></p>

Upvotes: 4

Related Questions