"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

In PATCH requests, JSON data is not transmitted through Ajax

I'm attempting to send JSON data from the client to my server with the following code: $.ajax({ url : 'http://127.0.0.1:8001/api/v1/pulse/7/', data : data, type : 'PATCH', contentType : 'application/json' ...

Stop the scrolling behavior from passing from one element to the window

I am facing an issue with a modal box window that contains an iframe. Inside the iframe, there is a scrollable div element. Whenever I try to scroll the inner div of the iframe and it reaches either the top or bottom limit, the browser window itself start ...

What is causing the color to be replaced by the latest selection?

I'm having trouble drawing three lines with different colors. They all end up being the same color, which is the last color specified in my code snippet below: function initObject() { var lineLength = 10; geometry = new THREE.Geometry ...

Is there a way to prevent automatically scrolling to the top of the page when submitting a form?

Resolved! By enclosing the input tag within an anchor tag, the issue has been resolved. The question may appear confusing at first, so let me provide some clarification. I created a mail form using PHP. This form is located at the bottom of the page. Whe ...

Seeking a JavaScript tool specialized in compressing POST data?

Currently working on a chrome extension that sends HTML strings to a server using POST requests. Interested in compressing these large strings before sending them. Wondering if there are any JavaScript libraries that can help with this? ...

Encountering difficulties accessing props while invoking a component in React

In my project, I've created a component called FilterSliders using Material UI. Within this component, I passed a prop named {classes.title} by destructuring the props with const { classes }: any = this.props;. However, when I try to access this prop ...

Combining v-on:click and v-link in Vue.js

I'm currently working on a Vue.js application and I am in the process of creating a login system that involves multiple components. Within my App.vue component, which serves as the main component with the navigation bar, there is a button that looks ...

Jade not responding to AngularJS click directive function

This tutorial is inspired by the MEAN Stack demo: Mongo, Express, AngularJS, and NodeJS I am attempting to incorporate a 'delete' method into my controller in the Jade template as shown below: characters.jade script function CharactersCont ...

Creating a Mondrian-inspired design using a combination of red, blue, and yellow within an HTML table

Is there anyone who can assist me in recreating this painting using HTML <table> tag and CSS within a browser? The image to replicate: https://i.stack.imgur.com/84y4I.jpg I attempted to complete this task, but my instructor is dissatisfied with th ...

Exploring the globe with 3D raycasting, orbit controls, and dynamic camera rotation

It would be great if users could hover over the small spheres in different countries to get more information. Initially, I thought using a raycaster would help achieve this, but it's not responding to mouse movements as expected. It seems like the is ...

How can you determine the status of an individual checkbox within a reactjs (material-table) component?

In my project, I have implemented a table that displays a list of students retrieved from a database. Upon clicking on each student row, a modal popup appears showing another table with 4 rows and 3 columns. Each column in the modal contains 4 checkboxes. ...

Customized queries based on conditional routes - expressjs

Can we customize queries based on optional routes? app.get('/:category/:item?', function (req, res) { var category = req.params.category; var item = req.params.item; var sqlQuery = 'SELECT * FROM items WHERE category = ? AND item = ?&a ...

Challenges arise when IE distorts featured images in a Wordpress theme

I've set up a Wordpress theme that utilizes featured images as header images on pages to allow clients to easily make modifications themselves. The header image container needs to be a fixed size (100% width of the page and 300px height), so I'm ...

Include a custom HTML element on a webpage using Python's Selenium module

I am looking to modify the HTML of a webpage by adding an element. Prior to modification: div p something /p /div Post modification: div form p something /p /form /div Is it feasible to accomplish this task? I would greatly appreciate any guidance. Than ...

Tips for aligning one item in the center and another item on the right with MUI v5

My goal is to center 3 navigation tabs in the middle of my page and have a dropdown on the far right for sorting. I managed to get the dropdown on the far right, but I'm having trouble perfectly centering the 3 navigation tabs inside the <Box> & ...

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...

Select items from object based on a specified array of IDs

I am facing a challenge with my list of objects that each have an array associated with them. For instance, take a look at this example: "-KpvPH2_SDssxZ573OvM" : { "date" : "2017-07-25T20:21:13.572Z", "description" : "Test", "id" : [ { ...

Unable to retrieve basic profile data from LinkedIn Members using their email ID unless they are signed in

I am struggling to retrieve the basic profile details of Linkedin Members using their email ID. Despite my efforts, I haven't been able to find relevant information in the documentation. My attempt involved creating an app, initializing the JavaScrip ...

Add a new element to the page with a smooth fade-in animation using jQuery

var content = "<div id='blah'>Hello stuff here</div>" $("#mycontent").append(content).fadeIn(999); Unfortunately, the desired effect is not achieved with this code. I am trying to create a sleek animation when adding new content. ...

Guide on utilizing Vercel KV for storing and fetching posts from an API

Looking to optimize your API by utilizing Vercel KV for storing and retrieving posts? If you have a basic node.js express API that pulls random posts from MongoDB, the process of integrating Vercel KV can enhance performance. Initially, the API will resp ...