Ahmad Adel
Ahmad Adel

Reputation: 59

how to make "type effect" in JavaScript?

this code should type one letter from the string myText every 200 MilliSecond to be like Type Effect, but it's type undefinded instead of letters.

var myText = "loremloremloremloremloremloremloremloremloremloremloremlorem",
    myButton = document.getElementById("Button"),
    result = document.getElementById("type"),
    i;
myButton.onclick = function (){
    "use strict";
    setInterval(function(){
        result.textContent += myText[i];
        i++;
    }, 200);
}
<p id="type"></p>
    <button  id="Button">Click!</button>

Upvotes: 0

Views: 38

Answers (3)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

You could wrap this in a re-usable function and add a check to see how many of the characters have been written.

You can cancel the interval, once you have reached the end of the string.

You can enclose additional parameters inside the interval, by passing them in after the timeout.

const myText = "loremloremloremloremloremloremloremloremloremloremloremlorem";

document.getElementById('my-button').onclick = (e) => {
  autoType(myText, '#type-1', 50);
  autoType(myText, '#type-2', 100);
}

function autoType(text, target, timeout) {
  target = typeof target === 'string' ?
      document.querySelector(target) : target;
  let intervalId = setInterval((options) => {
    if (options.index >= text.length - 1) {
      clearInterval(intervalId);
    }
    target.textContent += text[options.index];
    options.index++;
  }, timeout, { index: 0 });
}
<p id="type-1"></p>
<p id="type-2"></p>
<button id="my-button">Click!</button>

Upvotes: 0

bitifet
bitifet

Reputation: 3669

Try

result.textContent += myText.substring(i, i+1);

In JS (short and imprecise explanation), with myText[1] you are trying to access the property "1" of the object String(myText).

Upvotes: 0

Samuel Dost&#225;l
Samuel Dost&#225;l

Reputation: 140

You are missing i = 0, initial value

Upvotes: 1

Related Questions