How can you ensure that an element returns to its original position after being animated in jQuery?

I want to add some animations to my website using jQuery, but I lack the skills to create them from scratch. I have managed to copy some code snippets, but I am facing an issue with one of my animations. When I click a button, the block animates, but I want it to return to its original position after the animation ends. This way, multiple clicks on the button won't take the block too far away. Here is the code I am using:

HTML

<div id="button">Click here</div>
<div id="square"></div>

CSS

#square { width:100px; height:100px; position:relative;}

JavaScript

$( "#button" ).click(function() {
$( "#square" ).animate({
left: "-=60px",
}, 400);
});

Is there a way to make the square return to its initial position after the animation is complete?

Answer №1

One alternative to utilizing jquery animate is to develop a CSS animation and activate it by adding a class. CSS animations typically revert to their original state unless specified otherwise. For reference, please visit here.

Answer №3

To achieve smoother animation, I recommend utilizing a combination of JavaScript and CSS.

Here is an example snippet:

$("#button").click(function() {
  $("#square").addClass("animate").delay(400).queue(function(next) {
    $(this).removeClass("animate");
    next();
  });
});
#square {
  width: 100px;
  height: 100px;
  position: relative;
  background: red;
  transform: translate3d(0, 0, 0);
  transition: transform .4s linear;
}
#square.animate {
  transform: translate3d(-60px, 0, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button">Click here</div>
<div id="square"></div>http://stackoverflow.com/questions/40795871/jquery-how-to-make-an-element-comeback-to-initial-position-after-animation/40795957#

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

What is the best way to verify reCAPTCHA v2 on an HTML website?

The code I'm using is giving me an error when the page loads: Cannot connect to reCAPTCHA. Please check your connection and try again. Just a reminder, I won't be incorporating any server-side code on my website. It's a simple HTML setup ...

Is there a way to extract a single value from an array of data and convert it into a series of values separated by commas, all using JavaScript but without

Here is an array data in a specific format: const data= [ { name: "productname", id: "1356", price: "0.00", category: "Health", position: "1", list: "New Products", ...

Is it commonplace for redux to generate an abundance of storage?

I'm noticing a lot of lines in the terminal, is it really necessary to create so many storage instances? 4. The WrappedApp just created a new store with withRedux(MyApp) { initialState: undefined, initialStateFromGSPorGSSR: undefined } 14:47:39.619 ...

Can you guide me on how to programmatically set an option in an Angular 5 Material Select dropdown (mat-select) using typescript code?

I am currently working on implementing an Angular 5 Material Data Table with two filter options. One filter is a text input, while the other is a dropdown selection to filter based on a specific field value. The dropdown is implemented using a "mat-select" ...

What is the best way to reassign key-value pairs in JSON mapping using JavaScript/TypeScript?

Given {"a": {"name": "king", "firstname": "Thomas"},"b": {"age": "21"}} I'm exploring a simple way to convert it to {"name": "king","firstname": "Thomas","age": "21"} In the realm of Javascript/Angular. Any helpful suggestions are greatly appreci ...

Utilizing JQuery for retrieving a filename

I have a unique file upload button on my website. To provide the user with visual feedback about their chosen file, I modify the html of a div to display the file name. My jquery code is as follows: $("input[type=file]").change(function() { var filen ...

Updating a specific property for each object within an array of objects in MongoDB, and inserting the object if it does not already exist

I am looking for a solution to update a property for each object in an array of objects. If some of the objects do not exist, I want to insert the missing objects instead. Currently, I have been using "upsert", which creates a new document when no documen ...

Refresh the CSS without having to reload the entire page

I am working on a web page that operates on a 60-second timer. The code snippet below is responsible for updating the content: protected void RefreshButton_Click(object sender, EventArgs e) { ReportRepeater.DataBind(); ReportUpdatePane ...

PHP code fails to set a hidden element within a form array

My current project involves sifting through a modest PHP application to debug and enhance it. One snag I've come across is that what should be updates are instead treated as deletes and inserts. To rectify this, I've made some adjustments. Speci ...

Bootstrap 4 Row failing to fill entire div width

I am currently designing a bootstrap 4 layout with four columns, but starting with just three. I have an outer div container and an inner row with three columns. However, when I add borders to all the containers, I notice that the row does not expand to fi ...

The state remains constant upon clicking

Below is the code snippet of my component: import React from "react"; import { useState } from "react"; import { Text, SvgContainer, Svg, Flex } from "../lib/styles"; import Modal from "./Modal"; const Credits = () ...

Arrangement of HTML divs and styling classes

I have been experimenting with divs and classes in order to achieve proper alignment of text on my website. Currently, I am working with 2 classes that I would like to display side by side to create 2 columns. However, the right column containing the text ...

"Utilizing lightbox JS to produce a centralized overlay across the entire webpage

Currently in the process of redesigning a gallery for a client at www.stagecraft.co.uk/gallery.html I am encountering some challenges with my overlay. I want it to be centered and on top of any divs that are currently in view, as new images from the clie ...

The Vue template is not able to recognize the Pug language syntax within the .vue file

According to the Vue documentation: Template processing differs from other webpack loaders, as pug-loader and similar template loaders return a function instead of compiled HTML. Instead of using pug-loader, opting for original pug is recommended. Test ...

Is there a way to retrieve posts by year and month using nextjs and contentful?

Currently, I am in the process of setting up a blog using Next.js and Contentful CMS. The structure of my folders is set as follows: pages/blog/[year]/[month]/[slug].js Each year and month folder contains its own index.js file. Currently, my focus is on ...

What is the best way to split strings in an input field?

My task is to create a form with an input field and a dropdown list containing options for Checkbox and Radio. The user should enter text in the input field and select a type from the dropdown. For example: Input field: One, Two, Three Radio The expecte ...

Challenges with the Express server console

I have configured an Express Server and everything appears to be functioning correctly. The content I send is rendered in the browser, and my console.log test statements are being displayed in the terminal. However, when I inspect the browser page, nothi ...

Update email address depending on the option chosen from the dropdown menu

My contact form includes the following fields: Name Email Number Department Message The "Department" field is a drop-down selection with seven options: Audio Engineering Graphic Design Music Production Photography Videography Web Development Other I ...

Experiencing problems with the Locale setting when utilizing the formatNumber function in Angular's core functionalities

I am having trouble formatting a number in Angular using the formatNumber function from the Angular documentation. Here is my code snippet: import {formatNumber} from '@angular/common'; var testNumber = 123456.23; var x = formatNumber(Numb ...

Populating a select dropdown menu with options pulled from SQL table entries

Within my database, there is a table named "Registration" which is used for registering into clubs. This table consists of two columns: 'clubName' and 'registrationStatus'. The clubName column contains the names of different clubs, whil ...