When using .animate() to set the position, it takes precedence over manually assigning

I'm facing an issue with constantly scrolling objects on the screen, each assigned a number. When you press one of their numbers, it should move far left off the screen and then scroll back on. However, when I try to reassign the position of the element using offset, it only disappears for a moment and then continues scrolling where it was before. It seems like the animate() function is still running while I attempt to change it, causing it to briefly shift positions before being taken back by the animation. How can I override the animate function when it is called from a different function?

Below is the code segment where I manually assign the position:

$(document).ready(function(){
    $(document).keyup(function(e){
        if(e.which == 48){
            $('#foo').offset({top:8, left:-600});
        }
    });
});

And here's the animation function in action:

$(document).ready(function(){
    setInterval(function(){
        $('#foo').animate({
            left : "+=10"
        },{ duration: 200, queue: false });
    },200);
}

Answer №1

The animation is based on the previous settings. By setting a global variable, as Rooster suggested, you can easily manipulate it. You can try implementing something like this code snippet. If it doesn't work, create a Fiddle so I can assist you further.

$(document).ready(function(){
    var leftPosition = $('#foo').position().left;
    $(document).keyup(function(e){
        if(e.which == 48){
            leftPosition = -600;
            $('#foo').offset({top:8, left:leftPosition});
        }
    });
    setInterval(function(){
        leftPosition +=10;
        $('#foo').animate({
            left : leftPosition
        },{ duration: 200, queue: false });
    },200);
});

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

Concatenation in JavaScript replaces only the first character of a string

Objective My current task involves extracting SQL statements from a log file and performing simple string concatenation to add a semicolon (;) at the end: var query = line[i] + ";" Issue Expected output: insert into [...]; Actual output: ;nsert into ...

The React.useCallback hook in Cube.js is missing a dependency, specifically 'pivotConfig'. This could potentially cause unexpected behavior in the application

After multiple attempts at creating a straightforward dashboard using Cube.js with Windows 10 and MySQL version 8, I am feeling frustrated. Initially, I experimented with a JavaScript backend, struggled through the installation process for days, then attem ...

Thumbnail display issue in jQuery Galleria

After successfully setting up the Galleria Plugin, I found that the thumbnails for each picture were not generating. Here is my code: <div id="galleria"> <img title="Image title" src="images/1.jpg"> ...

Transform an array of strings into an array of floating point numbers using AngularJS

Hey everyone! I'm having trouble converting an array of strings into floats. When using map(parseFloat), I'm only getting integer numbers. Could the issue be with the commas in 40,78 causing parseFloat to interpret it as 40 instead of 40.78? Her ...

Tips for aligning an icon in the middle of the Bootstrap 3 grid vertically

Struggling with vertical centering an icon at the end of a list item. The goal is to vertically center the right arrow on the page. Using Bootstrap 3, Angular-UI bootstrap JS, and AngularJS. Current code snippet: <style> .center { display: in ...

What are the steps for sorting objects in an array by their data type attribute?

I am currently working with a JavaScript array of people objects that is dynamically rendered from JS. My goal is to implement a filter on the objects based on the selection made in the dropdown menu and matching it with the department attribute specified ...

Customizing HTML element tags in MUI: Best practices

Using the most recent version of MUI (v5) and incorporating CssBaseline from @mui/materials. Typically, in CSS, I would set up my styles like this: body, html, #root { width: 100%; height: 100%; min-height: 100%; margin: 0; padding: 0; font-siz ...

Images placed side by side, creating a dynamic and visually appealing layout

Can anyone help me figure out how to display three photos like this? https://i.sstatic.net/wD5At.png The photos cover the full width only if I set the css width: 100vh for all, but then the middle photo becomes disproportionate (black frames show how I wo ...

Different ways to manipulate the CSS display property with JavaScript

Having trouble changing the CSS display property to "none" using JavaScript. Check out my code: <div class="mydiv" onClick="clickDiv1()">hello</div> <div class="mydiv" onClick="clickDiv2()">hi</div> <div class="mydiv" onClick=" ...

Displaying a div when hovering over it, and keeping it visible until clicked

I want to display a div when hovering over a button. The shown div should be clickable and persistent even if I move the cursor from the button into the shown div. However, it should be hidden when moving out of the entire area. I'm unsure about how ...

Updating div width in Laravel blade using expressions or jQuery can be a simple task

Is there a way to dynamically change the width value of a div element based on a variable? The div contains blocks, and the size of each block is determined by the variable. For example, if $t->spotdiff = 2, I would like two equal blocks in a column wit ...

One method I use to retrieve ajax data and assign it before rendering the view

Despite putting the ajax.get in the created function, I am still unable to retrieve the ap_name value. This issue is related to vue.js created: function () { ajax.get('/envs').then(function (res) { this.apName = res.AP_NAME; ...

Troubleshooting ER_BAD_FIELD_ERROR in a node mysql stored procedure

Encountering an error message while executing the following code: Error: ER_BAD_FIELD_ERROR: Unknown column 'employee_id' in 'field list' Output: { employee_id: '6', employee_name: 'test', employee_contact: ...

Creating a CSS auto center for elements, with a unique twist

I have a design layout like this: Click here to view the image My auto-centered content is styled with the following CSS: width: 960px; margin: 0px auto; Within this auto-centered content, there is a DIV element that needs to span the full width of the ...

Unexpectedly, Ajax call is triggering additional callbacks

I am currently facing an issue with my AJAX request in the code below. The Chrome Inspector is showing that the callback function associated with the request is being called twice, resulting in the response being logged into the console twice. Additional ...

The step-by-step guide to deactivating server-side JavaScript on MongoDB using a Java application

I am working on a Java web application that interacts with a MongoDB Atlas database for CRUD operations. My goal is to disable server-side JavaScript for my Atlas instance directly from the Java web application itself. After researching, I came across th ...

Encountering ExpressionChangedAfterItHasBeenCheckedError during ngOnInit when utilizing Promise

I have a simple goal that I am working on: I want to display data obtained from a service in my component. This is how it used to work: In my component: ... dataSet: String[]; ngOnInit(){ this._service.getDataId().then(data => this.dataSet = da ...

Executing a C# program that sends a web request without using JavaScript

My goal is to programmatically download the contents of a website, but it seems like this content is being loaded through ajax calls. Interestingly, when I disable javascript in my browser, only one request is made by the page and all the content is displa ...

Identifying click events using jQuery specifically

After a jQuery event is triggered on a form by a click event only, I want to add some code. The event may also be called in other situations. To detect when the event is triggered, this code can be used: $( ".grouped_form" ).on("wc_variation_form", funct ...

Encountering silence: React JS fetch call left unanswered by Sinatra server

Exploring the realms of Sinatra and React JS, I am venturing into making a GET call from my React website to a Sinatra server in order to display plain text. The Sinatra Server script: require 'sinatra' set :root, 'lib/app' before d ...