Javascript Help: Typewriter Effect Debugging

How can I ensure that there are spaces in between each word?

Wix Studio | Velo | Javascript

In Wix Studio, I created a text box and added javascript to it, using Velo, to create a typing effect. However, once I run the script, the spaces between each word in the sentences are removed.

I’ve tried using non-breaking spaces.

Test site: https://byashleenicole.wixstudio.io/briancajohnson
it’s the 3rd section. ignore all other issues for now.

let sentences = [
   "running your business", 
    "building your brand", 
    "increasing your impact", 
    "gaining visibility"
];
let currentSentenceIndex = 0;
let currentLetterIndex = 0;
let textElement = $w("#typewriterText"); // Use the correct ID
let typingSpeed = 100; // Speed in milliseconds for typing
let pauseBetweenSentences = 500; // Pause after each sentence

function type() {
    if (currentLetterIndex < sentences[currentSentenceIndex].length) {
        // Add each character to the text property
        textElement.text += sentences[currentSentenceIndex].charAt(currentLetterIndex);
        currentLetterIndex++;
        setTimeout(type, typingSpeed);
    } else {
        setTimeout(deleteText, pauseBetweenSentences);
    }
}

function deleteText() {
    if (currentLetterIndex > 0) {
        // Remove the last character
        textElement.text = textElement.text.slice(0, -1);
        currentLetterIndex--;
        setTimeout(deleteText, typingSpeed);
    } else {
        currentSentenceIndex++;
        if (currentSentenceIndex >= sentences.length) {
            currentSentenceIndex = 0; // Loop back to the first sentence
        }
        setTimeout(type, pauseBetweenSentences);
    }
}

$w.onReady(function () {
    textElement.text = ""; // Clear the text initially
    type(); // Start typing effect
});

That recursion is a very interesting way to implement this effect

I believe the reason for your error is that when you set a text to something that ends with a space, Wix truncates and removes it

'running ’ becomes ‘running’, and then ‘y’ is added

Quite a few ways of implementing around that
But aside from custom code - have you seen this?

1 Like

thank you so much! this is much easier l0l