"Enhance Your Website with Dynamic List Item Animations in

Working on a simple animation involves removing classes from list items once they are loaded and added to the document. However, I am encountering issues with the animation execution. I aim for a stepped animation pattern as depicted below...

https://i.sstatic.net/kMMtP.gif

The problem is that while the console.log messages are displayed in a stepped manner during the loop, the removal of classes occurs simultaneously once the loop completes. How can I alter this behavior? Why do the console.log messages step through but the classList.remove action does not?

Below is the code snippet...

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}


/**/
function showListItems() {
  var listItems = document.querySelector('.idList');
  var n = 20;
  var c = 0;
  var itemArray = new Array();
  for (var i = 0; i < listItems.children.length; i++) {
    var item = listItems.children[i];
    if (item.classList && item.classList.contains('idList__item--hide')) {
      console.log('Item: ', item);
      itemArray[c] = item;
      c++;
    }
  }
  console.log('Item Array: ', itemArray);
  itemArray.forEach(function(el, index) {
    sleep(n);
    el.classList.remove('idList__item--hide');
    console.log("EL[" + index + "]: ", el);
  });
}

I understand the complexity of this code and have tried various approaches such as promises, for loops, and the forEach method.

Your assistance is greatly appreciated.

Answer №1

The browser remains unrefreshed until the completion of JavaScript execution. Your script holds onto control without releasing it back to the browser while idle, causing the lack of updates. This is precisely why setTimeout exists.

Replace

itemArray.forEach(function(el, index) {
    sleep(n);
    el.classList.remove('idList__item--hide');
    console.log("EL[" + index + "]: ", el);
});

with

itemArray.forEach(function(el, index) {
    const ms = n * (index + 1);
    setTimeout(function() {
        el.classList.remove('idList__item--hide');
        console.log("EL[" + index + "]: ", el);
    }, ms);
});

We are scheduling all the remove functions in advance by multiplying n with index + 1.

And if you're curious, here is the code snippet I utilized to compare sleep versus setTimeout. https://codepen.io/rockysims/pen/jeJggZ

Answer №2

While not the most conventional method, this approach may help resolve your issue.

One potential solution is to employ setTimeout() within a forEach loop, utilizing the index parameter to adjust the timing as shown below:

itemArray.forEach(function(element, index) {
    setTimeout(function(){
         element.classList.remove('idList__item--hide')
    }, 500 * (index + 1)) 
});

Answer №3

I implemented a combination of Jquery each and setTimeout functions to create a chain of animations.

$( "li" ).each(function( index ) {
    var listItem = $( this );
    setTimeout(function() {
      listItem.animate({
      opacity: 1
    }, 500); 
    }, (index + 1) * 500);
    
});
ul {
  padding : 20px;
}
ul li {
  list-style : none;
  height : 50px;
  background-color : lightgreen;
  margin : 20px;
  opacity : 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Hello world 1</li>
<li>Hello world 2</li>
<li>Hello world 3</li>
<li>Hello world 4</li>
</ul>

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

"Revolutionize real-time data updates with Node.js, Redis, and Socket

Greetings! I am currently working on a project for my school that involves creating a "Twitter clone." My goal is to incorporate a publish subscribe pattern in order to facilitate real-time updates. One key feature users will have access to is the abili ...

Find any consecutive lowercase or uppercase letter and include one more

I have a task in Javascript that I need help with. The goal is to insert a special character between a lowercase and uppercase letter when they are matched together. For example: myHouse => my_House aRandomString => a_Random_String And so on... T ...

Currently trapped within the confines of a Next.js 13 application directory, grappling with the implementation of a

I need to figure out how to export a variable from one component to layout.tsx in such a way that it is not exported as a function, which is currently causing the conditional check in the class name to always be true. Below is the code snippet: // File w ...

Proceed to the next request after the initial request has finished executing in node

Imagine there is an endpoint called /print. Each time a request is sent to this endpoint, it triggers the function printSomething(). If another user hits this endpoint while printSomething() is still processing, it will run the function again simultaneousl ...

What is the best way to utilize an AngularJS directive to send a POST request with all parameters from a form?

I have created a custom AngularJS form with Stripe integration using a directive. You can view the Fiddle for this project here: https://jsfiddle.net/u5h1uece/. HTML: <body ng-app="angularjs-starter"> <script src="https://js.stripe.com/v3/"> ...

What is the method for calculating values entered into dynamic input fields?

I am facing a slight issue with my HTML form code... Within my code, there are several input fields that are being generated dynamically. Each dynamic input field contains a numerical value which I need to use for mathematical calculations. The calculati ...

The Flask AJAX request is returning an empty ImmutableMultiDict, whereas the same AJAX request successfully works with http.server

Making the switch from http.server to Flask has caused issues with my image upload functionality using AJAX. This is being done in Python 3. Attempts at troubleshooting that have failed: I have ensured multipart/form-data is included in the Ajax req ...

JavaScript click event to open a URL in a new window

I am trying to create a hyperlink with text using HTML, and I want it so that when the user clicks on it, it redirects to a specific URL. I am new to JavaScript! Here is my code: <a class="dt-button add_new_table_entry DTTT_button DTTT_button_new" tab ...

Having trouble retrieving values for jVectorMap? The getElementById method doesn't seem to be functioning as

I have been trying to set markers on a jVectormap. I retrieve the content from my database and store it in a hidden input field. The format of the data is as follows: {latLng:[52.5200066,13.404954],name:'Berlin'},{latLng:[53.0792962,8.8016937],n ...

Angular App Failing to Validate Session Cookie 'sessionId' in AuthGuard

Encountering a perplexing issue with my Angular application where the AuthGuard fails to recognize a session cookie named 'sessionId' correctly. I have successfully implemented user authentication, and the expected behavior is for users to be dir ...

Incorporating SVG line elements into a line graph

After successfully creating an interactive line chart using nvd3, I am now looking to enhance it by adding an svg line to represent a baseline. Within my function that constructs and displays the line chart, I have the following code: function _buildGrap ...

How come the hidden container does not reappear after I click on it?

I'm having an issue with a hidden container that holds comments. Inside the container, there is a <div> element with a <p> tag that says "Show all comments". When I click on this element, it successfully displays the comments. However, cli ...

mention a Vue.js component computed property that points to a specific DOM element

Is there a way to access the DOM element that initiated a method inside a Vue component computed property? For example: <template> <img :src="getUrl" class="image1"/> <img :src="getUrl" class="image2"/> </template> <scri ...

Is there a way for me to customize the appearance of the Material UI switch component when it is in the checked

I am seeking to customize the color of the switch component based on its checked and unchecked state. By default, it displays in red. My goal is to have the "ball knob" appear yellow when the switch is checked and grey when it is not. This styling must be ...

Error: Attempting to access the 'map' property of an undefined variable, cart

My project consists of two main components, App.js and Cart.js. I am utilizing material-ui and commerce.js API for this application. import React , {useState , useEffect} from 'react' import Products from './Components/Products/Products&apos ...

To calculate the sum of input field rows that are filled in upon button click using predetermined values (HTML, CSS, JavaScript)

Greetings for exploring this content. I have been creating a survey that involves rows of buttons which, when clicked, populate input fields with ratings ranging from 5 to -5. The current code fills in one of two input fields located on opposite sides of ...

A lesson is what I'm seeking, as I face an Uncaught TypeError: Unable to locate the property 'split' of an undefined value

Although this question has been asked multiple times before, I am a beginner and eager to learn. I would greatly appreciate it if someone could take the time to explain this to me. I have tried to find a solution to this error using the existing answers, b ...

Adding embedded attributes from a different object

I am facing a challenge with two arrays called metaObjects and justObjects. These arrays consist of objects that share a common property called id. My goal is to merge properties from the objects in these separate arrays into a new array. const metaObje ...

Automatically scrolling down a div as new content is added using XMLHTTPRequest.openConnection

https://jsfiddle.net/kv5gbamg/ - I created a jsfiddle to demonstrate the functionality of the system Essentially, I am seeking a way to automatically scroll the scrollbar to the bottom every time a new message is received. My system updates the div with ...

ReactJS library encounters "Failed to load PDF file." error intermittently while attempting to view a PDF file

I recently developed a React JS application using create-react-app and decided to incorporate react-pdf for viewing PDF files. However, I've encountered an intermittent issue where the PDF sometimes fails to load. Specifically, when I initially load t ...