Unlimited image rotation with JQuery

I'm currently working on a project where I have a series of images that are moving left or right using the animate() function. My goal is to create a loop so that when the user clicks "next", the last image transitions to the first position seamlessly. However, I'm having trouble figuring out why the line $(this).css("left", "-320px"); isn't working correctly within the if statement below.

$("#right").click(function(){
  $("#sliderWindow").find("img").each(function(i) {
    var left = $(this).css("left");

    $("#imageContainer" + i).animate({"left": "+=220px"}, "slow");

    left = parseInt(left);
    left += 220;
    left = left + "px";

    if(left === "1220px") {
      //I'm puzzled as to why this isn't functioning as expected
      $(this).css("left", "-320px");
    }
  });
});

Answer №1

Your code seems a bit messy, but I believe your statement is functioning, even if just momentarily.

It appears that the issue arises when setting the position of the <img> elements returned by find("img") to those of your elements with the ID "imageContainerN". This might be due to setting the position while an animation is in progress, causing the element to jump to -320px and remain there until the next animation takes place shortly after.

You could try restructuring the code like this (with the crucial change being the order in which the animation and test occur)...

$("#right").click(function() {
    $("#sliderWindow").find("img").each(function() {
        if (this.offsetLeft >= 1220) {
            $(this).css("left", "-320px");
        }
        $(this).animate({left: "+=220px"}, "slow");
    });
});

Explanation

Consider the process of setting up an animation in jQuery.
1) jQuery notes the requested movement of +220px from the current position
2) For instance, if the image is currently at 100px, jQuery plans to move it from 100px to 320px over a specified duration
3) Once the animation starts, jQuery disregards the image's current position and simply calculates where it should be based on the animation parameters for each tween

During the animation, if you then attempt to reposition the element with an if statement, the following scenario may unfold over time...
1) Animation calculated based on parameters (starting at 100px, ending at 320px)
2) After 10 milliseconds, the image moves to 102.2px
3) Your code runs (assuming it evaluates true for the current position of 102.2px)
4) The image is repositioned to -320px by your code
5) The next tween occurs after 10ms and moves the image to 104.4px (making it appear as though the image was never moved to -320px)
6) Subsequent tweens continue moving the image to 106.6px, 108.8px, and so on, until it reaches 320px

I hope this clarifies the situation. While I have not delved into the jQuery animation code, this is likely the process at play.

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

jQuery does not have the ability to manipulate a partially rendered content that was fetched via AJAX in Rails

One feature of my application is the ability to create "memos" and reply to other memos using @ tags within your own memo. For example: Hello, this is in response to @123 When you click on @123, memo #123 will be displayed beneath the memo you are curr ...

By default, the text area element in Vue or Nuxt will send a message to the console

Every time I include a textarea html element in my Vue/cli or Nuxt projects, this message appears in the console. Is there a way to prevent this message from showing up in the console? <textarea rows="5" cols="33"> This is a textarea. < ...

What is the method for a Greasemonkey script to divide a link into three interconnected links?

My goal is to use Greasemonkey to link Redmine issue numbers found in cgit commit messages to their respective issues or projects. The cgit commit message HTML source looks like this: <a href='/editingmodule/commit/?id=49e4a33e0f8b306ded5'&g ...

Implementing data updates in Ruby on Rails through AJAX or jQuery

Within a text field input lies the value of a database attribute (ref). Upon focusing on the field, a border appears and disappears upon clicking out. My dilemma is that I wish for the data within the text field to be saved in the database without the nee ...

How to extract dynamic content efficiently by combining Selenium and Scrapy for multiple initial URLs

I have been assigned the task of developing a web scraper for a property website where the data will be collected and stored for future analysis. The website is a national platform that requires users to select a region before displaying any results. In ...

What are the steps to resolve a Fetch request issue with a Node.js server?

I am attempting to make a simple POST request using the fetch method. I am working on building a contact form using Vanilla Javascript, HTML, and CSS on the front end, while utilizing Node.js / Express on the backend. Take a look at my front end code: ...

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

AngularJS Error Present in Chrome Only

While this code works perfectly in Firefox and IE, it encounters an issue in Chrome. An error occurs at the ".find" line which results in a "TypeError: undefined is not a function". angular.forEach(data, function(data) { pointInfoFactory.ge ...

Lazy Loading fails to deliver for Ajax Requests

I recently integrated lazy loading following David Walsh's advice (tip 1) and it initially worked perfectly. However, I encountered an issue when the images were filtered and reloaded with an ajax request. The website is built on Rails, and the images ...

Issue with MERN stack: User not being saved in mongoDB despite lack of errors

Check out the repository at https://github.com/QexleLLC/Otlic After running the frontend with npm start, and starting the backend with nodemon server, everything appeared to be working fine. However, when I tried signing up by going to localhost:3000/sign ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

JavaScript SQL results in either a string or an object after executing a

I am facing an issue with the following query: sql = client.query("SELECT * FROM monitormaterialsept", function (err, result, fields) { if (err) throw err; console.log(result); }) I am unsure of what the output of the sql variable is. Is there a ...

Issue with jquery_ujs: Font Awesome spinning icon animation functions properly in Chrome but not in Safari

I've integrated font-awesome-rails into my Rails project. When a user clicks the submit button on a form: The submit button should display an animated font-awesome spinner and change text to "Submitting...". The button must be disabled to prevent m ...

Incorporating a feature that displays one show at a time and includes a sliding animation into an

Hey there! I have this show/hide script on my website that's been working well. However, there are a couple of things I need help with. I want to modify the script so that only one div can be shown at a time. When a div appears, I'd love for it ...

Trouble with hide/show loop in setTimeout function

I have a special animation with 3 text items that are initially invisible. The goal is to make these items appear one by one with a delay of 2 seconds after clicking a button. Each item should be visible for 1 second before fading out and making way for th ...

I'm trying to use Route.get() but it seems I forgot to include a callback function. What mistake did I make?

I've searched through various answers on different platforms, but I'm still struggling to understand. What mistake have I made? Can someone provide assistance? *revised. I have included requiring routes and app.use. It seems like the function is ...

What exactly does the Javascript object syntax signify? (specifically in a Vue script)

Can anyone explain the purpose of this statement and the difference between using const and var? const { SearchIcon } = myApp.icons; I am currently exploring Vue and still relatively new to Javascript. This code snippet appeared in a tutorial example. The ...

Step-by-Step Guide: Ensuring Only One Menu Item is Active at a Time in AngularJS

How can I make only one menu item active at a time? Currently, when I click on a specific menu item, all menu items become active. I need to remove the previous active menu item and set the currently clicked menu item as active. Can someone assist me with ...

Implementing dynamic checkbox values depending on a selection from a dropdown menu in Angular

In my checkbox list, I have various Samsung mobile models and two offers available. $scope.offers = [ { id: "as23456", Store: "samsung", Offer_message:"1500rs off", modalname: "Samsung Galaxy You ...

Is there a way to stop users from altering form values on a webpage by using the "inspect" tool in their browser?

Currently, I am developing an application using node.js and handlebars as the view engine. One issue I am facing is that when a form is submitted, it inserts data into the database. The problem arises because the form passes values that are hidden from the ...