The element's position remains unchanged after the .click re-event in the function

Welcome to my first attempt at using jQuery! Please bear with me as I navigate through this learning process. Here's the challenge: I have a series of elements in my HTML.

<div class="garden">
    <div class="point left">&#9668;</div>
        <div class="trees">
            <div id="apple">Apple</div>
            <div id="cherry">Cherry</div>
            <div id="pear">Pear</div>
            <div id="oak">Oak</div>
            <div id="fir">Fir</div>
        </div>
    <div class="point right">&#9658;</div>
</div>

I am trying to move the elements to the left after clicking "pointLeft", and to the right after clicking "pointRight". When an item is at the leftmost position and "pointLeft" is clicked, that item should be removed, a copy created, and placed at the rightmost position. For instance, when you click on "pointLeft", "cherry" moves to the spot where "apple" was, "pear" moves to the spot where "cherry" was, and so on. Additionally, the animation feature (.animate()) needs to be incorporated. Initially, I am attempting to animate one element without using .clone().

$(document).ready(function() {
    var trees = ["#apple", "#cherry", "#pear", "#oak", "#fir"];
    var treePosition = [];
    for (var i = 0; i < trees.length; i++) {
        treePosition.push($(tree[i]).position());
    }

    function changePositionLeft() {
        if ($("#apple").position()) {
            $(trees[0]).animate(treePosition[4]);
        }

        else if ($("#apple").position() == treePosition[4]) {
            $("#apple").animate(treePosition[3]);
        }
    }

    $(".point.left").click(function() {
        changePositionLeft();
    });
});

After the first click, "apple" successfully moves to the position of "fir". However, upon the second click, "apple" does not animate to treePosition[4]. Could someone please explain why there is no animation after the second click, and suggest a solution? Thank you!

Answer №1

After reviewing the provided code snippet, it appears that the condition in the if statement will always be true:

if ($("#apple").position()) {

The function being checked here will never return a value that evaluates to false (such as 1,2,3,4,5). It actually returns the coordinates of the element on the page in an object format, which will not be interpreted as false.

If the if statement returns true, then the following code is executed:

$(trees[0]).animate(treePosition[5]);

Since the array used here seems static and is not updated with the new positions of elements, it still refers to '#apple'. Ideally, storing references to DOM elements rather than their IDs would be more appropriate.

To address this, I've made some modifications to your code. Instead of using an array for element positions, I animate the movement of each element to its new position and then shift the first element to the end. This way, clicking the button triggers the animation from front to back seamlessly.

Here's the revised changePositionLeft function:

function changePositionLeft() {

    var trees = $('#trees');

    trees.children().each(function(index, child) {
        if (index == 0) {
            $(child).animate(trees.children().last().position());
        } else {
            $(child).animate(trees.children().eq(index - 1).position());
        }
    });

    trees.children().first().appendTo(trees);
}

Check out the updated fiddle: http://jsfiddle.net/8kkfw7mu/5/

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

Having trouble with updating label text in MUIDataTable in ReactJS?

Looking to implement multi-language support in MUI Datatables. I have been able to modify the translations, but when attempting to change languages by providing a different object with new translations (verified using console log), the label texts do not u ...

Aligning a div in relation to the background image

I am seeking guidance on how to center a Div Box and make it responsive relative to the background image. The div box should be contained within the white box, similar to the example shown here: body{ font-family: 'Roboto Mono', monospace; ...

What is the best way to reset an angularJS form after it has been submitted

I am trying to figure out a way to clear form fields on a modal window after the user executes the save method. I have attempted using $setPristine in AngularJS, but it's not working as expected. Any suggestions on how to achieve this task? Here is t ...

"Utilize Regular Expressions to conceal part of a text string with a

Looking for a way to conceal part of a string using JavaScript? For example, wanting to mask the second and third segments of a credit card number like this using regex: 4567 6365 7987 3783 → 4567 **** **** 3783 3457 732837 82372 → 3457 ****** 82372 ...

Why isn't the jQuery click() function functioning on my modified HTML?

I am trying to create a unique version of the go-moku game using different programming languages and databases. My aim is to enhance the game's functionality by incorporating jQuery, PHP, and a MySQL database. var moveCount = -1; setInterval(function ...

The flexbox layout is not properly stacking div rows in a column

Objective: Creating a flexbox layout with a responsive background image that adjusts in height when the screen size changes, causing elements to wrap; In addition, there is a fixed header bar at the top of the page. The layout consists of a full-screen co ...

Looking to eliminate curly braces from a string?

Despite my efforts to search through the site, I am still unable to resolve the issue at hand. var blah2 = JSON.stringify({foo: 123, bar: <x><y></y></x>, baz: 123}); This is what I attempted: blah2.replace(/[{}]/g, ""); Here&apo ...

Top method for displaying and concealing GUI elements upon a click event

I would like a dat.GUI() instance to appear when a mesh is clicked, and disappear when it is clicked again. Furthermore, if it is clicked once more, I want it to reappear. Despite trying various approaches, I have been unable to achieve the desired behavio ...

Table sorting feature with checkboxes has disappeared from view

This segment of code includes HTML for a table along with JavaScript functionality. When a checkbox is clicked, another table will be displayed: <form class="filter"> <input type="checkbox" id="checkboxID" class="unchecked"> EG <input type= ...

Issue with autoplay slideshow functionality not activating when opened in a new tab

The owl.carousel.js plugin is used for creating a jQuery slideshow. Initially, the slideshow works correctly, but I noticed that the autoplay feature stops working when I open a new tab in Firefox or Chrome. Demo : Demo : $(document).ready(function () ...

How can I implement a for loop in Node.js?

I am currently experiencing an issue with my for loop while attempting to retrieve data from MongoDB and display it in the browser. The problem is that it only iterates through once, resulting in only the first entry being output. Strangely enough, when ...

Enhancing the readability of modals with Angular Dialog Service

I have been utilizing the Angular Dialog Service to create popup forms on my website. The source code for this service can be accessed here: https://github.com/m-e-conroy/angular-dialog-service/blob/master/README.md However, I am experiencing an issue wit ...

Using Aurelia CLI: Incorporating npm package containing image assets into your Aurelia CLI application

Currently, I am attempting to incorporate lightslider (jquery slider library) from NPM into my Aurelia CLI 0.23.0 project. In order to achieve this, I have updated the dependencies in aurelia.json as follows: { "name": "lightslider", ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

Can we dynamically add an identical DOM structure by clicking a button using jQuery?

I currently have ten text fields within a single div. I am interested in including another set of ten text fields with the same name, class, and id. Is there a way to recycle the existing DOM structure mentioned above, or will I need to generate and add t ...

Is there a way to rearrange my divs in the mobile display?

Is there a way to make the image column stack below the text info column in mobile view? I've tried using flexbox without success, so any help would be greatly appreciated. Thank you! <div class="container"> <div class="row"> ...

What's the best way to add a Grid to a TabPanel in React without triggering any pesky warnings?

I have a question that should be clear from the context. I'm currently working with Tabs from Material-UI to display different Grids based on the user's selection. Each panel is supposed to contain a Grid with various text fields and components. ...

Enhancing UI-Grid: Implementing Dynamic Field Addition in the Header Name Section

There is a grid with a field named Users, and the requirement is to display the count of Users in the header name of a ui-grid. How can I achieve this? This snippet shows my JavaScript file code: var userCount = response.usercount; columnDefs: [{ nam ...

Issue with passing parameters to function when calling NodeJS Mocha

I have the following function: export function ensurePathFormat(filePath: string, test = false) { console.log(test); if (!filePath || filePath === '') { if (test) { throw new Error('Invalid or empty path provided'); } ...

Trigger an event upon completion of a write operation in AngularJS

I want to trigger a search after my user finishes typing (without hitting enter) in AngularJS. Here is a simplified version of my HTML: <div ng-class="input-append" ng-controller="searchControl"> <input type="text" ng-model="ajaxSearch" ng-cha ...