"Enhance Your Website with Dynamic Text Effects using JavaScript

Is there a way to continuously animate text during the loading process of an AJAX request? I've tried implementing various methods, such as using a setTimeout function or an infinite loop, but nothing seems to work for repeating the animation once it's finished. Can someone please shed some light on why this is happening?

document.getElementById("generateButton").addEventListener("click", function() {
  var loadingIndicator = document.getElementById("loadingIndicator");
  loadingIndicator.style.display = "block";

  var chars = document.querySelectorAll(".char");
  var delay = 0;

  function repeatAnimation() {
    chars.forEach(function(char) {
      setTimeout(function() {
        char.style.animationName = "bounce";
      }, delay);
      delay += 100; // Adjust this delay to control the sequence
    });

    setTimeout(repeatAnimation, 1000); // Launch the next repetition
  }

  var descriptionValue = document.getElementById("description").value;
  var titleValue = document.getElementById("title").value;

  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/generationDescription", true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      loadingIndicator.style.display = "none";

      if (xhr.status === 200) {
        var response = JSON.parse(xhr.responseText);
        document.getElementById("description").value = response.description;
        document.getElementById("shortDescription").value =
          response.shortDescription;
      }
    }
  };

  var data =
    "description=" +
    encodeURIComponent(descriptionValue) +
    "&title=" +
    encodeURIComponent(titleValue);
  repeatAnimation();
  xhr.send(data);
});
@keyframes bounce {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.loading-indicator .char {
  display: inline-block;
  animation-duration: 1s;
  animation-fill-mode: both;
  animation-name: none;
}
<div id="loadingIndicator" class="loading-indicator" style="display: none;">
  <span class="char">C</span>
  <span class="char">h</span>
  <span class="char">a</span>
  <span class="char">r</span>
  <span class="char">g</span>
  <span class="char">e</span>
  <span class="char">m</span>
  <span class="char">e</span>
  <span class="char">n</span>
  <span class="char">t</span>
  <span class="char"> </span>
  <!-- Space between words -->
  <span class="char">e</span>
  <span class="char">n</span>
  <span class="char"> </span>
  <!-- Space between words -->
  <span class="char">c</span>
  <span class="char">o</span>
  <span class="char">u</span>
  <span class="char">r</span>
  <span class="char">s</span>
  <span class="char">.</span>
  <span class="char">.</span>
  <span class="char">.</span>
</div>

Answer №1

The issue you're facing is that the animation doesn't repeat once the AJAX request is done. This happens because the animation starts before sending the AJAX request, and there's no way to pause or restart it after the request finishes. Using setTimeout to repeat the animation isn't an effective solution.

Give this code a try;

document.getElementById("generateButton").addEventListener("click", function () {
  var loadingIndicator = document.getElementById("loadingIndicator");
  loadingIndicator.style.display = "block";

  var chars = document.querySelectorAll(".char");
  var descriptionValue = document.getElementById("description").value;
  var titleValue = document.getElementById("title").value;

  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/generationDescription", true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      loadingIndicator.style.display = "none";

      if (xhr.status === 200) {
        var response = JSON.parse(xhr.responseText);
        document.getElementById("description").value = response.description;
        document.getElementById("shortDescription").value = response.shortDescription;
      }
    }
  };

  var data =
    "description=" + encodeURIComponent(descriptionValue) +
    "&title=" + encodeURIComponent(titleValue);

  xhr.send(data);

  // Begin the animation loop after the AJAX request
  var animationInterval = setInterval(function () {
    chars.forEach(function (char) {
      char.style.animationName = "bounce";
    });
  }, 1000);

  // End the animation loop once the AJAX request is complete
  xhr.onload = function () {
    clearInterval(animationInterval);
  };
});

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

PHP-generated HTML often contains unnecessary and excessive indentation

I'm trying to adjust the indentation of my HTML generated by PHP, but I'm facing issues removing some unwanted indentations. Take a look at this snippet from the HTML source: <table id="structure"> <tr> <td id="navigation"> ...

Is it possible to update the version of NPM?

Having an issue with installing packages for my React-Native project due to a NPM version error. How can I upgrade it? Currently using version 4 ...

`Can you teach me how to dynamically load HTML elements using input JSON data?`

What is the best way to iterate through an input array of objects? I currently have data for only 2 people included. However, there are more than 50 people's information in the input and I need to loop through all of them. Here is a sample code snip ...

Guide to adding information to a file in Nodejs depending on a condition

Looking for assistance on how to append an annotation (@Circuit(name = backendB)) to a file if the "createEvent" name exists and the annotation is not already present. I am unsure of the process, so any help on checking and appending using streams would ...

Embed an external website within a div element

Is there a way to embed an entire external website onto another site, without scroll bars or borders? I attempted this method but the entire page did not load, and there were still scroll bars and borders present. <!DOCTYPE HTML> <html> <b ...

How can I make Material UI's grid spacing function properly in React?

I've been utilizing Material UI's Grid for my layout design. While the columns and rows are functioning properly, I've encountered an issue with the spacing attribute not working as expected. To import Grid, I have used the following code: ...

I am disappointed with the lack of functionality in Angular's HTML type inference

When working inside an Angular component, I want to select a div element by id or class. This method works menuDisplayDiv = document.getElementsByClassName("some_class")[0] as HTMLDivElement; menuDisplayDiv = document.getElementById("some ...

What is the best way to show checkbox selections based on my database structure?

Two variables, one for checkboxes and the other for checked values are causing an issue in displaying them from controller to view. The code to handle this in the controller is as follows: $scope.infoParticipant = functionThatGetsParticipants(); ...

When properties are passed and then mapped, they become undefined

While I experience no errors when directly mapping the array, passing the same array through props results in an error stating "Cannot read property 'map' of undefined." Brands Array const brands = [ { key: 1, Name: "Nike", }, { ...

Redirecting script upon successful connection detection

I have created a script that checks for internet connectivity using an image, and redirects if internet is available. However, the issue is that it caches the images, leading to attempts to load them even when offline. Is there a different approach I can ...

Click on the window.location.href to redirect with multiple input values

I am facing a challenge with my checkboxes (from the blog label) and the code I have been using to load selected labels. However, this code seems to only work for one label. Despite multiple attempts, I have found that it only functions properly with one ...

Drawing a line beneath the mouse's center using JavaScript

Struggling with my JavaScript drawing tool, particularly the draw() function. The line is consistently off-center below the mouse cursor. How do I fix this issue? My aim is to have the line always follow the center of the mouse as it moves. Could someone c ...

What is the proper way to implement JQuery within a constructor function contained in a JavaScript namespace?

Yesterday I ran into a problem when asking about using JQuery inside a JavaScript constructor function within a namespace. There was a bug in my code that caused me to get the answer to the wrong question. var NS=NS||{}; NS.constructor=function() { t ...

Bringing in a feature within the Vue 3 setup

At the moment, I am attempting to utilize a throttle/debounce function within my Vue component. However, each time it is invoked, an error of Uncaught TypeError: functionTD is not a function is thrown. Below is the code snippet: useThrottleDebounce.ts imp ...

I could really use some assistance with the concept of "AJAX" - can anyone help

After spending several months working with AJAX, I have come to understand the typical request lifecycle: Sending parameters to a background page (PHP/ASP/HTML/TXT/XML ... what other options are available?) Performing server-side processing Receiv ...

The Art of Repeating: Navigating through a Multi-Layered Array

My PHP Array looks like this: $fruits = array( array("Apple", 1.25), array("Banana", 0.86), ); Desired HTML Output: I want the HTML output to be formatted as follows: Fruit: Apple Price: 1.25 Fruit: Banana Price: 0.86 Attempts Made: I tried ...

Activate browser scrollbar functionality

Below is the HTML code snippet: <html> <head> <style> #parent { position : absolute; width : 500px; height : 500px; } #top { position : absolute; width : 100%; height: 100%; z-index : 5; } #bottom { position : absolute; width : 100%; ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...

Reduce the amount of time it takes for a Google AdWords Script to generate a

According to Google Script best practices, it is recommended to store operations in an array and then call the methods once all the operations have been constructed. This helps minimize response time each time a service is called. For example, let's ...

Filtering URLs using Firefox extension

As the page loads, multiple HTTP requests are made for the document and its dependencies. I am looking to intercept these requests, extract the target URL, and stop the request from being sent if a specific condition is met. Additionally, plugins may als ...