How do I make a typewriter effect with cursor and backspace?

Hi there, I’m trying to make a typewriter effect that shows a cursor and backspaces the text before typing out the new text.

I’ve looked at similar posts and either they’re outdated or the links they forward to are broken.

I got a live example on my website, but not sure if I can post links here.

#yourText is a text field that contains the original text, which is then erased by the erase() function (You can leave it empty, set origText to the text you want, and currtext to “”).

The blinking line is just a regular vertical line. You put them together in a container with a grid that has a left side that you set to auto width, right side is 1fr. Put the text on the left side and the line on the right side.

let origText;
let currText;
let textfield;
$w.onReady(function () {
    textfield= $w('#yourText') //textfield where the text will be put
    origText = textfield.text;  //The original text
    currText = origText;    //The text currently being displayed
    erase()
    blink()
});

//Removes the last letter until nothing is left, then starts the write() function
function erase() {
    let intervalID = setInterval(function () {
        currText = currText.slice(0, -1);
        textfield.text = currText
        if (currText.length == 0) {
            setTimeout(function () { write() }, 300)
            clearInterval(intervalID)
        }
    }, 400);

}

//Adds letters until all have been added, then starts erase()
function write() {
    let intervalID = setInterval(function () {
        currText += origText.charAt(currText.length)
        dinBedrift.text = currText
        if (currText.length == origText.length) {
            setTimeout(function () { erase() }, 300)

            clearInterval(intervalID)
        }
    }, 400);
}

//makes the vertical line blink
function blink() {
    const linje = $w('#blinkingLine');
    setInterval(function () {
        if (linje.hidden) {
            linje.show()
        } else {
            linje.hide()
        }

    }, 600);

}

Thanks! What’s:

dinBedrift.text

Woops, I changed names of things so that they would be easier to read, but forgot to change one

dinBedrift.text=currText

Was supposed to be

textfield.text=currText

That’s a really great way @simen

Is there a way to define multiple words in an array as the text field to loop continously?

It’s very possible, I just unfortunately don’t have the time to write it any time soon.

The TL;DR is, make the array with the words you want. At the start of write() set origText to the array element. And use a counter to cycle trough them (if at the end of array start back at 0)