Challenges with incrementing in Jquery's each loop and setTimeout

http://jsfiddle.net/fxLcy/ - an example showcasing the use of setTimeout.

http://jsfiddle.net/fxLcy/1/ - this demo does not include setTimeout. Although all elements are correctly positioned, I am in need of that delayed animation =/

My goal is to arrange 6 cards per row using CSS transition and setTimeout. However, I am facing a challenge where I cannot use increment for my left and top parameters within setTimeout, as it accumulates all increments and places the elements in their final positions prematurely.

var self = $(this);
if (increment % 6 === 0 && increment !== 0) {
    topIncrement++;
    leftIncrement = 0;
};
setTimeout(function() {
    self.css({
        'left' : 10 + leftIncrement * (resizedWidth + 20),
        'top' : $("#controlPanel").height() + 10 + topIncrement * (resizedHeight + 20)
    });
}, increment * 500)
leftIncrement++;
increment++;

Answer №1

One issue you are facing is that the variable is being shared across different timeouts. You need the JavaScript code to capture the x and y positions separately for each timeout (you need a snapshot of the x/y values using JavaScript closure).

To solve this problem, modify the setTimeout function in your code like this (refer to the updated fiddle):

var valuex = 10 + leftIncrement * (resizedWidth + 20);
var valuey = $("#controlPanel").height() + 10 + topIncrement * (resizedHeight + 20)
setTimeout(function() {
    self.css({'left' : valuex,
    'top' : valuey});
}, increment * 500)

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

Checking a sequence using a list of strings

I have an array containing a list of IDs: var listId: string[] = []; var newId: boolean; for (let i in data.chunk) { listId.push(data.chunk[i].aliases[0]); } My objective is to compare a new ID with the entire list. If the new ID is found in the list ...

Ways to retrieve the content from a textfield

Is there a way to retrieve text from a textfield in material UI without using the onChange method? It just seems odd that I would need to constantly track the value with onChange in order to use it for any other purpose. I decided to search for solutions ...

When retrieving data from a JSON file, only display the value instead of showing the entire

When a user tries to login, I have created a modal window. If the user enters incorrect credentials, it returns SignInStatus.Failure, which is fine. However, the page then refreshes and only displays the number "3" at the top of the page with no other cont ...

Send a res.json response and retrieve it using res.render in a different router

Trying to retrieve a JSON from the route "/api/product" and display it using hbs on the "/product" route. The code seems to be working, but is it done correctly? The router in this case is: '/api/product' router.get('/', this.controll ...

Is it possible to utilize the output of a function to determine the styling of a div element in Vue?

Hi, I'm trying to use the v-bind:style in my div to apply the textposit function with the textpos prop as a parameter. The function should adjust the style of the div based on the value of the parameter. <div class="container" :style=&qu ...

What is the best way to dynamically incorporate Before After CSS code in Vue?

I am facing a unique challenge in my current project. I need to dynamically apply colors from data inside a v-for loop, specifically for the :after CSS pseudo-element. While normal CSS properties are easily applicable, I am struggling with applying styles ...

Use the Vue `this.$router.push` method inside a setTimeout function

I have a landing page '/' that users will see first when they visit our website. I want to display a loading wheel for 5 seconds before automatically redirecting them to the login page '/login'. My Landing.vue page in Vue and Bulma.io ...

Is it not possible to generate HTML tags using jQuery and JavaScript in JSF?

I'm currently working with jsf 2.0 and richfaces 4.0 to develop my application. Occasionally, I incorporate jQuery and JavaScript functions for displaying and hiding elements. However, I've encountered an issue when trying to generate tags within ...

Utilizing a shared service for multiple JSON datasets in AngularJS: A beginner's guide

After successfully creating a service that retrieves data from a local JSON file and uses it in a controller to display it in the browser, everything seems to be working well. Here is the code snippet: JavaScript Code: var myApp = angular.module("myApp", ...

Node.js exporting fails due to an undefined variable

When attempting to export variables in Node.js, I keep receiving an undefined error. I'm not sure what the issue is, can anyone provide assistance or suggestions? Here is a snippet from index.js: var test = 10; module.exports.test = test; And here i ...

Updating line connections between objects in Three.js while rendering

I am working with a three.js canvas that contains circles moving independently. Initially, these circles are connected by a single line that follows the same geometry as their positions. However, I am facing difficulty updating the line's geometry wh ...

Currently, I'm developing a Django project and integrating django_bootstrap_icons. Despite successfully installing it with pip and completing all necessary steps, the icons are not displaying on the website

configurations.py INSTALLED_APPS = [ ... 'myapp', 'django_bootstrap_icons', ] ... STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'static,'media') STATIC_ ...

Words program with the header feature incorporated

Hello, I am currently working with Laravel to build an HTML page and have successfully converted it to MS Word. However, I am now trying to add a header inside. Can anyone help me achieve this? Here is a snippet of my code: <body> <a class= ...

Using inertia-links within the storybook framework

Hey there, just wanted to share my experience with storybook - I'm really enjoying it so far! Currently, I'm facing a challenge while implementing it in my Laravel app with Inertia. I'm trying to render a navigation link component that make ...

Extracting specific data from a JSON subnode within an HTML document

I have been attempting to retrieve product data (name, price, url), along with information on available sizes and colors, from a website that is formatted in JSON (https://www.bergzeit.de/marken/salewa/). However, I am struggling to locate the 'elemen ...

Make a tab the active tab within the Material-UI tab component

For the current project, I have decided to utilize Material UI as the primary library. One of the pages in the project requires four tabs, which I am implementing using the tab component from the Material UI library. By default, when rendering the page wi ...

How to prevent jQuery from continually recalculating width on window resize?

Here is the code I've been working on: http://jsfiddle.net/7cXZj/ var callback = function () { $('.progress-bar').width($('.progress-bar').parent().width() - 190); $(".mainpart-background").animate({ width: "80%" }, 80 ...

Issues with Bootstrap Carousel Fade Transition and Button Controls inoperable

I am currently exploring the creation of a carousel on bootstrap that transitions smoothly between three images (specifically 3 'gorilla' jpgs). However, I am encountering some challenges while learning HTML. Challenge 1: The carousel is not tra ...

Customize YouTube iframe styles in Angular 4+ with TypeScript

Has anyone been successful in overriding the style of an embedded YouTube iframe using Angular 4+ with TypeScript? I've attempted to override a CSS class of the embed iframe, but have not had any luck. Here is the URL to YouTube's stylesheet: ...

JavaScript Firebase: Service worker malfunctioning during navigation

I'm currently developing a website that relies on firebase messaging. To make this happen, a specialized service worker for firebase has been integrated into the site. This website functions as a webchat platform where messages are synchronized and s ...