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

Using Angular to Bind JSON Data

I'm currently in the process of evaluating different JS frameworks for a project and I find myself torn between Angular and Ember. As I continue to explore Angular, I have a specific question regarding data binding to an external json file stored on S ...

Implementing user-driven filtering in a React table

When a user clicks on the submit button, data will be loaded. If no filter is applied, all data will be displayed. const submit = async (e: SyntheticEvent) => { e.preventDefault(); const param = { ...(certificateNo && ...

Issue with unrecognized expression in JQuery when processing Ajax response

Recently, I implemented a JQuery Ajax Form on my website. $('#modal-body-sign-in').on('submit', '#sign-in', function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr(&apo ...

ng-repeat count filter not refreshing multiple times

Looking at a list with filters attached, I am trying to count the items and show a message if there are no items... <li ng-repeat="item in items = (items | sortWithTab:tab | filter:search")> {{ item.name }} </li> <div ng-if="items.lengt ...

Transfer data in an array within value="" separated by ':' through AJAX/JSON in PHP and HTML

Can data be passed in array form using AJAX/JSON? For example, like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."? Here is a sample code snippet to illustrate this: if(sqlsrv_num_rows($query) > 0 ...

How can Javascript split main.js into two separate files using import or require?

Currently, my main.js file is functioning perfectly despite its length. However, I am interested in organizing my code by separating the functions related to 'y' into a separate file. In PHP, this process can be easily achieved with require(&apos ...

Tips on customizing image borders/masks with hover effects

Is there a React library or a simple CSS trick to create an image's canvas cropping effect on hover? For example, similar to this: Thanks in advance! ...

JavaScript: Creating an array of images from a directory

I've encountered a problem that has proven to be more complex than expected - I am struggling to find resources related to my specific question. My goal is to store 36 images from a folder on my computer into an array using Javascript. Below, you will ...

Creating a custom navigation bar that elegantly fades away with a smooth animation as you scroll down the page is a must-have

How can I create a navigation bar that disappears when scrolling, with a smooth animation? This is the progress I have made so far. HTML: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/style.css" type="tex ...

Utilizing the `filterBy` function with a custom select list that changes dynamically

I'm currently in the process of constructing a form with an extensive selection of drop-down items utilizing vue.js. My approach involves implementing the dynamic select list as detailed in this documentation: However, I am interested in providing us ...

Text fields do not show a cursor icon

On the website http://www.legrandclub.net, there are two text fields. Everything works fine in all web browsers except for Internet Explorer. When I click on one of the text fields, the cursor is not displayed, although it is possible to write text. What c ...

When using window.location.href and location.reload(), the updated page content from the server is not loaded properly

Currently, I am working on a form that is being updated via an AJAX call. Once the AJAX call successfully completes, I want to reload the page in order to display the new changes. Even though I tried using location.reload() and window.location.href after ...

Transforming CSS with React Router Links

Why is my CSS being significantly altered by the React Router Link? Is there a way to prevent the Link from affecting the styling? Without Link: With Link: This is the code for the Link. It does not have any style properties. <Link to={`/link/${i ...

Is it permissible to utilize the ::Before::Before element?

While working on a CSS file for a page with a non-editable profile, I encountered the challenge of not being able to add content directly. This limitation prompted me to explore alternative solutions. My idea was to utilize the page ID and incorporate it ...

The Ajax request fails to pass the value to the controller

I've spent the entire day debugging this method and I'm in need of some assistance. My goal is to make an API request and for each array it returns, I want to send a post request to my controller method. However, despite console.log showing the c ...

Sending Ajax requests to web services hosted on a dual-node NLB

I am currently managing a two-node NLB configuration where multiple web services need to be accessed from the client-side using ajax POST requests. When visiting the page at: http://clusternode1/ everything works smoothly. Similarly, when accessing it f ...

Excessive screen height causes the CSS box layout to overflow

I am looking to create a screen layout similar to the one shown in this image. It should consist of a row with no overflow and include: A left box that contains: A fixed height header (20px), An aspect square box taking up the remaining height. ...

Utilizing JSON data within Highcharts

I am currently using a column high chart to display some data. I am making an AJAX call to return JSON data. [{"department":"DESIGNING","Present":8,"Total":44},{"department":"SEO","Present":0,"Total":1},{"department":"COORDINATION","Present":1,"Total":2}] ...

Issue with Vuetify carousel not resizing to fit the entire width and height

I am looking to create a carousel that spans the entire width and height of a viewport in my Vue.js 2 project using Vuetify. Below is the code I have so far: <head> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500, ...

Having Trouble with Click Function: Loading Pages into Div using Jquery/Ajax

Struggling to load content from other pages into a specific div by clicking on a URL link? Despite having previously executed the code successfully, it seems to redirect to the linked page instead of loading in the desired div. Even with an alarm set up as ...