Modifying the location of an element in an array with jQuery

Using jQuery and JavaScript


       var movableItems = new Array();
       movableItems.push($('#cloud1'));
       movableItems.push($('#comment1'));

        if(leftPressed == true){ 
            for(var i = 0; i < movableItems.length; i++){
                var currentPosition = movableItems[i].position().left;
                currentPosition += 10;
                movableItems[i].css("left", currentPosition);                   
            }
        }
    

I'm attempting to move a group of objects across the screen when the left arrow key is pressed. I have added two objects to an array, then looping through the array to increment each object's position and update its CSS. However, the position of the objects remains unchanged which I am verifying using:


        alert(
            "Size: " + movableItems.length +
            "\nIndex 0: " + movableItems[0] +
            "\nLeft: " + movableItems[0].position().left + 
            "\nTop: " + movableItems[0].position().top 
        ); 
    

Can you identify what's causing it not to work? Or suggest a better approach. Thank you!

Corrected code:


        for(var l = 0; l < movableItems.length; l++){
            var tmpPosX = movableItems[l].position().left;
            tmpPosX += amount * 10;
            movableItems[l].css("left", tmpPosX);                   
        }
    

Answer №1

.position() is actually a method that retrieves the position rather than setting it.

To learn more, visit: http://api.jquery.com/position/

Using

movable[i].offset({left:movable[i].position().left+10})
should achieve the desired result in this context.

For additional information, check out: http://api.jquery.com/offset/#offset2

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

Is it possible to prevent iPhone from resizing when the address bar is hidden or shown?

I am currently working on an unconventional website with a quirky design. It is meant to have a visually appealing layout with plenty of animations and full responsiveness. The main body element is set to overflow: hidden; and the structure is as follows: ...

How can I pass command line variables into an npm script?

I am facing an issue where I am attempting to pass a command line option (which is not stored in version control) to my main script index.js. This script performs specific actions based on a designated S3 bucket. Here is the relevant section from my packa ...

An uncaught exception has occurred: An error was encountered indicating that the specified path is not valid for either posix or windows systems, and it appears that there is no 'join' method defined in the

I am currently working with nextjs version 13.5.6 using the app router and app directory. This issue arises during the compilation of the route app/(home)/page.js. The folder and file structure within the app folder is as follows: app/ -(home)/page.js -ser ...

Sticky Navigation Error: Issue with accessing property 'top' of an undefined element

I'm currently working on incorporating a feature into my website where the navigation style changes as you scroll through different sections. The main distinction I've noticed is that I am developing a sticky navigation bar that becomes fixed on ...

CSS text wrapping will now occur on underscores as well as spaces and hyphens

I am facing an issue with long file names in my HTML formatting causing overflow. These file names use underscores instead of spaces, making it difficult to wrap them properly. For example: Here_is_an_example_of_a_really_long_filename_that_uses_underscore ...

Progressive rendering of particles in THREE.js

I am new to the world of 3D and I'm trying to render particles as they are created. My goal is to have these 2000 particles render individually as they are created, but with the current code, they only render once all particles have been created. I h ...

Exploring the Dynamic Duo: Laravel Echo and JQuery

After including Echo in Vue.js' resources/assets/js/bootstrap.js, one of my components is throwing an error The error message states: "Error in mounted hook: 'TypeError: $ is not a function'" When I remove the Echo import, everything run ...

Struggling to receive a response from request.POST.get within the index function of views.py

I am struggling to develop a web application that shows the IP Address of a hostname entered by the user in a text field. Unfortunately, I keep encountering an error where I can't seem to get a response from the URL. As a beginner in this field, I wou ...

Selenium: The ultimate guide to inserting text within a div element located inside an iframe

Snippet of HTML code: <div class="listRte__editorFrame"> <iframe src="about:blank" style="height: 150px;"> #document <html> <head> <body> ...

next-images encountered an error during parsing: Unexpected character ''

Having trouble loading images dynamically with next-images: //Working <Image src={require(`../../images/exampleImage.jpg` )}/> However, I want to use a dynamic URL like this: //Not working <img src={require(`../../images/${image}.jpg` )}/> Th ...

Rendering to a texture using the pingpong method in Three.js went smoothly, with no issues detected and the output was not

I attempted to implement the pingpong texture swap technique to generate smoke in threejs by following a tutorial that was published some years ago. Unfortunately, this tutorial utilizes an outdated version of threejs, and I am experiencing difficulties tr ...

Error: The function Object.setup() is undefined

I'm having an issue with my JavaScript setup function and array of ghost objects called ghosts. When I try to call the setup function on the last ghost object in the array, I receive this error message: Uncaught TypeError: ghosts[(ghosts.length - 1)]. ...

Open the overflow div within a table data cell

My goal is to create a drag-and-drop schedule tool similar to Fullcalendar. I have decided to use a table layout with a rectangular div inside each TD cell to represent tasks. <table onDragEnd={dragend}> <tr> <th>0</th> ...

Prompt for confirmation in ASP.NET code-behind with conditions

I've searched around for a solution to this problem. Below is a representation of my pseudocode: bool hasData = ItemHasData(itemid); Confirm = "false"; // hidden variable if (hasData) { //Code to call confirm(message) returns "true" or "false" ...

The filter method in combination with slice array functions is not functioning properly

My search input is used to filter an array of users displayed in a table. The table has pagination set up so that only 10 users are shown per page. Oddly enough, the search filter only seems to work on the first page. Once I navigate to another page, the ...

Enhance your search experience with Vue.js by highlighting important keywords across multiple search

I'm working on implementing a search feature that will bold the matching parts. For example, if I have the name 'John' and search for 'Jo Joh' in the same string, I want it to bold the part of 'John' that has the most mat ...

Styling <Link> component with styled-components: A step-by-step guide

Utilizing the Link component from @material-ui/core/Link in my TypeScript code was initially successful: <Link href="#" variant="body2"> Forgot? </Link> However, I am exploring the transition to styled-components located in a separate file. ...

External JavaScript is not functioning

I am encountering an issue with an external JavaScript file not working in my HTML document. Strangely, Firebug is not reporting any failures. However, when I directly run the JS code in my HTML file, it works perfectly. Here is the content of action.js: ...

Enhance Your Website with Php Jquery Autocomplete Feature!

In the main page, there is an autocomplete input field along with an [ADD button]. When the user clicks on the add button, they are redirected to a page to add a new record. After saving the new record, the user is then redirected back to the main page. ...

Link the selector and assign it with its specific value

Greetings, I am a newcomer to React Native and I am currently using Native Base to develop a mobile application. I am in the process of creating a reservation page where I need to implement two Picker components displaying the current day and the next one ...