Is it necessary to remove every letter before moving on to the following array position?

I've been working on a script to create an animated "self-writing text" effect. However, I'm encountering an issue where each word jumps to the next one instead of smoothly transitioning by deleting each letter before moving on to the next word in the array.

const text = ['design', 'make', 'develop', 'code', 'create']
let count = 0;
let index = 0;
let currentText = "";
let letter = "";

(function type() {
    if (count === text.length) {
        count = 0;
    }
    currentText = text[count];
    letter = currentText.slice(0, ++index);
    
    document.querySelector(".main__animation").textContent = letter;
    if (letter.length === currentText.length) {
        count++
        index = 0;
    }
    setTimeout(type, 500);
}())

Any help or suggestions would be greatly appreciated!

Answer №1

const words = [, 'design', 'make', 'develop', 'code', 'create']
let counter = 1;
let currentIndex = 0;
let currentWord = "";
let letter = "";
var isDeleting = false;

(function typingEffect() {
  if (counter === words.length) {
    counter = 1;
  }
  currentWord = words[counter];

  if (isDeleting) {
    letter = currentWord.slice(0, --currentIndex);
  } else {
    letter = currentWord.slice(0, ++currentIndex);
  }

  document.querySelector(".main-animation").textContent = letter;
  if (letter.length === currentWord.length) {
    isDeleting = true;
  }
  if (letter.length === 0) {
    counter++;
    currentIndex = 0;
    isDeleting = false;
  }
  setTimeout(typingEffect, 500);
}())
<div class="main-animation"></div>

Answer №2

Here is the solution I have come up with. If you have any questions, feel free to ask.

function createAnimation(words, target, speed) {
  let wordIndex = 0;
  let i = 0;
  let erase = false;
  
  const handler = () => {
    const word = words[wordIndex];
    
    if (erase) {
        target.innerText = target.innerText.slice(0, -1);
        
        if (!target.innerText.length) {
            wordIndex = (wordIndex + 1) % words.length;
            i = 0;
            erase = false;
        }
    } else {
        target.innerText += word.charAt(i);
        i++;
        
        if (i === word.length) {
            erase = true;
        }
    }
  };
  
  let interval = null;
  
  return {
      start() {
          interval = setInterval(handler, 1000 / speed)
      },
      stop() {
          clearInterval(interval);
      }
  }
}

const animation = createAnimation(
  ['design', 'make', 'develop', 'code', 'create'],
  document.getElementById('target'),
  5 // [letters/s]
);

animation.start();

// TO STOP, CALL animation.stop()
<h1 id='target'></h1>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for verifying phone numbers on an HTML form

Need assistance with validating a 10-digit number input. The first two digits must be either '05' or '06'. Seeking guidance on how to achieve this validation in PHP or JavaScript. Appreciate any help, thanks! ...

Can a variable be assigned to an innerHTML id?

Currently in the process of mastering JavaScript, one question that remains at the forefront of my mind: is it feasible to assign a variable to an ID? <div id="example"> Code </div> Is it possible for me to use document.getElementbyID("exampl ...

The content could not be created due to an inability to lazily initialize a collection of roles. The proxy could not be initialized as there was no

Encountering an error with FetchType.LAZY: Error message: failed to lazily initialize a collection of role: com.websystique.springmvc.model.User.userProfiles, could not initialize proxy - no Session Here is the model class in question: @SuppressWa ...

Beginning the process of setting up information windows for map markers with the help

As I work on dynamically adding info windows to Google Maps markers from a JSON array received from the server, I find myself grappling with Javascript's handling of variables and scope. One attempt involved this code snippet: $.getJSON("server", fu ...

Issues with Boostrap grid system on smaller screens

I'm attempting to design a flexible web layout that displays differently on various device screens. Here's the breakdown: 2 rows 6 columns (large screens, iPad Pro, and other devices) 3 rows 4 columns (iPhone 6/7/8 plus) 4 rows 3 columns (iPhone ...

Creating a CSS layout with tabs that include a visually appealing right space

My webpage is set up for tabbed browsing, with the tabs displayed as <li>s in block form. The parent div containing the tabs is floated to the right. However, I am encountering an issue where the last tab is not fully aligning with the right side of ...

Preventing page refresh with Javascript when clicking on CAPTCHA

I have been exploring a CAPTCHA tutorial on TutsPlus.com and I am facing an issue where the 'Incorrect Captcha message' keeps appearing, indicating that my user input through $_POST does not match the stored $_SESSION string. Upon investigating ...

Exploring Angular Route Configurations: Utilizing Multiple Outlets with Path as an Array of

In my Angular9 application, I have configured hundreds of routes paths. Is there a way to use multiple outlets with a single array of string paths? Current Code: const routes: Routes = [ { path: 'Data/:EntityID/:Date', compon ...

jquery-enhanced tabs with versatile functionality

HTML: <ul class="tabs"> <li><a href="#tab-one" class="current">Residential</a></li> <li><a href="#tab-two">Commercial</a></li> <li><a href="#tab-three">Agricultural</a></li> < ...

Using a WCF RESTful web service to handle POST requests and HTML forms

I have a simple .net Restful web service published on IIS: [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "formTestGET?firstInput={firstInput}&socondInput={socondInput}")] string formTe ...

I desire a smooth fade-in transition for the background image when the addClass function is

If the background color is set to header-fixed-position, the color will fade in. However, if the background is an image, the image will not fade in. Apologies for my lack of proficiency in English. Please refer to the sample code below. Try removing the c ...

Opt for buttons for color selection instead of a checkbox toggle

I attempted different approaches to replace the existing checkbox with a button but encountered difficulty. Using the onClick method also proved unsuccessful. VIEW DEMO HERE: https://jsfiddle.net/yxez4a2u/ HTML: <div class="form-check form-switch ...

transferring iterative information via ajax data flow

My form includes hidden input fields that are manually declared in the AJAX data without a loop. How can I efficiently loop through them in the AJAX data? Below is my form script: <form method="POST" name="myform"> <?php for($i=1;$i<=5;$i+ ...

`Trouble with CSS Measurement Properties in Internet Explorer 10`

(In the past, I relied on conditional IE statements to exclude a portion of my website from IE Browsers. Unfortunately, this method is no longer supported in IE10.) Currently, I have three images displayed on the header of my site, stacked one on top of t ...

Obtain Rails database queries in real-time

Is it possible to retrieve database results dynamically in Rails? For instance, if I have a list of cities indexed by ID, can I pass the ID to the view based on the city name, similar to this JavaScript method (even though I know this code won't work) ...

In Node.js, JavaScript, when using SQLite, the variables are inserted as Null

I have spent a lot of time searching and trying various methods, but I am still unable to solve this issue. My goal is to insert 8 variables received from an API call into an SQLite table. Although the execution seems correct, when I query the table, all v ...

Customizing the color of pagination in Bootstrap

Here is the pagination control I am working on: https://i.sstatic.net/iVufm.png I have been trying to change the color of the pagination labels to purple, but my CSS overrides are not working. Here is what I currently have in my stylesheet: /* Paginatio ...

Using a JavaScript onclick function to retrieve specific elements within the document

I'm attempting to extract the elements from the source that was clicked on, but for some reason it's not functioning correctly. Check out my JSFIDDLE Here's the HTML: <span class="populate" onclick="populate();" href="?id=1">Hello&l ...

Leveraging CreateBrowserRouter from React Router alongside a Redux store

I'm currently working on integrating Redux and React-Router into a React blog project. I am fetching data from an API and storing it in Redux, but for some reason, the data is not rendering and no error messages are being displayed. Here is the code ...

Send a request from my own local client without encountering any Cross-Origin Resource Sharing (C

I am attempting to send a request from my locally hosted Node.js/Express.js client to a third-party API that I have deployed on the cloud. Strangely, I keep running into a CORS error whenever I make the request. The interesting part is that the request wor ...