What is the best way to stop div animations when clicking with jQuery?

Upon loading the page, a div animates automatically. There is also a button present. When the button is clicked, I would like to create a new div and animate it the same way as the first one. However, when this happens, the position of the first div also changes due to the animation effect. How can I prevent the already animated div from moving when a new div is created?

<div class="wrapper">
    <div class="car"></div>
</div>
<button id="button">spawn new car</button>
$(document).ready(function() {
    var car = $('.car');
    car.animate({left:"+=367px"}, 2000);
    car.animate({top:"-=247px"}, 2000);

    $("#button").click(function () {
        $(".wrapper").append('<div class="car"></div>');
        var car = $('.car');
        car.animate({left:"+=367px"}, 2000);
        car.animate({top:"-=247px"}, 2000);
    });
});

Answer №1

Here is a method to exclusively move newly added div elements.

Simply add a temporary "move" class when adding the element, and then remove it after the animation is complete.

$(document).ready(function() {
    var car = $('.car');
    car.animate({left:"+=367px"}, 2000);
    car.animate({top:"-=247px"}, 2000);


    $("#button").click(function () {
        $(".wrapper").append('<div class="car move">car</div>');
        var car = $('.move');
        car.animate({left:"+=367px"}, 2000);
        car.animate({top:"-=247px"}, 2000);
        $(".car").removeClass('move');
    });
});
.car{
  position:absolute;
  left:0;
  top:0;
}

.wrapper{
  position:relative;
  top:0;
  left:0;
  width:100%;
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <div class="car">car</div>
</div>
<button id="button">spawn new car</button>

Check out this working example on Fiddle!

Answer №2

Just like you mentioned:

"However, when onclick() is triggered, the position of the first div also changes."

The reason behind this behavior is that you are applying the animate function to a class named car, and the first div also happens to have the same class name, causing its position to change as well.

A viable solution would involve assigning unique and dynamic class or id values.

One approach could be generating random IDs like so:

$("#button").click(function () {
        var id = Math.floor(Math.random() * 100) + 1;
        $(".wrapper").append('<div class="car_"'+id+'></div>');
        var car = $(".car_"+id+"");
        car.animate({left:"+=367px"}, 2000);
        car.animate({top:"-=247px"}, 2000);
    });

Answer №3

The reason for the animation is due to the creation of this fresh div, causing it to move further down the page. One solution could be to utilize absolute positioning to keep it fixed in one spot. However, this might give the appearance of a rigid layout. Another approach would be to apply a smoothing effect to the buttons' movement instead.

Answer №4

Give this a try

$(document).ready(function() {
var vehicle = $('.vehicle');
vehicle.animate({left:"+=367px"}, 2000);
vehicle.animate({top:"-=247px"}, 2000);


$("#button").click(function () {
    $(".wrapper .vehicle").removeClass('vehicle');
    $(".wrapper").append('<div class="vehicle"></div>');
    var vehicle = $('.vehicle');
    vehicle.animate({left:"+=367px"}, 2000);
    vehicle.animate({top:"-=247px"}, 2000);
});
});

This code snippet will eliminate the vehicle class from the current div and insert a new div with the vehicle class

Answer №5

Give this a shot! JSFIDDLE

 $(document).ready(function() {
        var ship = $('.ship');
        ship.animate({left:250, top:50}, 1500);


        $("#button").click(function () {
            $(".container").append('<div class="ship"></div>');
            var ship = $('.ship');
            ship.animate({left:250, top:25}, 1500);
        });
    });

    .ship{
        border:2px #333 solid;
        height:120px;
        width:120px;
        position:absolute;
    }

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

Android WebView does not support rendering Persian fonts

I am having an issue with applying a Persian font to my html content, which contains both Persian and English text. The CSS is correctly applied except for the font itself. In the CSS, I have defined the font-face like so: @font-face{ font-family ...

What is the best way to duplicate an image on both sides in a vertical manner?

I've successfully implemented a background image on the left side of the website, however, I'm facing difficulty in replicating the same effect on the right side of the webpage. <style> body { background-image: url('background. ...

The console is displaying an undefined error for _co.photo, but the code is functioning properly without any issues

I am facing an issue with an Angular component. When I create my component with a selector, it functions as expected: it executes the httpget and renders a photo with a title. However, I am receiving two errors in the console: ERROR TypeError: "_co.photo ...

Selecting JavaScript Libraries During the Development of a Web Application

Transitioning from PHP & Java/Android development to web app development can feel overwhelming, especially with the abundance of Javascript Frameworks available. Check out this comparison of popular JavaScript frameworks View a list of the top JavaSc ...

Create a layered structure using a specified path

I am aiming to create a function that can accept an object path, like { 'person.data.info.more.favorite': 'smth' } and then output a nested object: { person: { data: { info: { more: { favorite: 'smth& ...

Is there a way to retrieve two distinct data types from a single ng-model within a select option?

My mean stack code is functioning well, but I am looking to enhance it by adding a new feature. Specifically, I want to retrieve more elements from my NoSql database while selecting options. This is the structure of my database: Tir2 :id, price, xin, yin ...

Using Codeigniter to fetch a PHP array in an AJAX success callback

I have implemented a jQuery script to send the value selected from a dropdown menu to my controller. The controller then calls a function in my model to execute a query using this value, and retrieve an array of results from the database. These results are ...

Retrieve combination values through an AJAX request using ExtJS

My UI is developed using ExtJS, and I have a specific set of tasks that need to be executed when the page loads: Initiate an ajax call to the server to fetch a HashMap. Create a combobox within the main Panel on the page. var combo = Ext.create(' ...

Comparing getElementById with $('#element') for retrieving the length of an input field

Consider the following scenario: <input type="text" id="apple"> Why does the first code snippet work? $(document).ready(function () { alert($('#apple').val().length); }); However, why does the second code snippet not work as expecte ...

Server encountered an unexpected T_STRING error that was not present on the localhost

While my website runs smoothly on localhost, I encounter the unexpected T_STRING error when running it on a workplace server with PHP 5.3.3. The culprit seems to be the exportXML function: eliminating this function resolves the issue. Any suggestions? I&a ...

Prevent jQuery from hiding elements when hovered over. Implement clearTimeout when hovering over an element, and use setTimeout when moving

I am attempting to create a sidebar with two navigation buttons that hide after a delay when the mouse cursor stops moving. However, I'm encountering an issue - how can I prevent these elements from hiding when they are in a hover state? Where should ...

Would this be considered an effective way to utilize JQuery's queues?

Currently, I am working on a webpage that displays a list of users and I need to retrieve icons showing their Skype status from . However, I have encountered issues with the calls to mystatus.skype.com failing when sent simultaneously. To address this pr ...

Exploring the functionalities of PointerLockControls, incorporating WASD controls, and experimenting with Three.js

Forgive me if this is a beginner question, but I've noticed that in the official three.js examples, the PointerLockControls.js allows for mouse pointer lock and WASD key navigation. I have successfully locked the mouse pointer, but I am having troubl ...

Change the way a button interacts with a different element

Currently, I am utilizing SlickSlider from http://kenwheeler.github.io/slick/ and attempting to integrate the Next and Prev buttons with other elements (specifically spans within another container). I have attempted the following: $('button.next&apo ...

Datatables fails to execute page transitions

It seems like I must be missing something, even though my code is quite basic and closely follows the example provided on the web. I am currently using server-side paging. The issue I'm facing is that upon initial page load, the data from the server ...

Enhance the flight experience of a helicopter with jQuery game by adding smoother controls

I'm currently experimenting with creating a basic game. In this game, the user controls a helicopter and can fly it up and down. Although I have successfully implemented the basic functionality where holding the screen makes the helicopter ascend an ...

Achieve Efficient Data Input in Django with JQuery Ajax for Multiple Forms

I am interested in carrying out a task similar to the one demonstrated in this video: https://youtu.be/NoAdMtqtrTA?t=2156 The task involves adding multiple rows to a table and then inserting them all into the database in a batch. Any references or sample ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

What is the best way to center align tabs in a Bootstrap 4 list?

I am working with tabs structured like this: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/> <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist"> <li class="nav-item"> ...

What is the right way to nest a SCSS rule for a specific selector within a list using the "&" symbol?

I have a question that I couldn't find the answer to in any documentation or on Stack Overflow. While this example may not be perfect, it should give you a basic understanding of what I'm trying to achieve. Illustration .btn-group { .btn ...