Reverse the CSS animation direction

I am facing an issue with an animation that moves in one direction. I am looking to reverse the animation so it goes back to its original position:

$('#right').click(function() {
  $('.container').removeClass('.move-left').addClass('move-right');
});
$('#left').click(function() {
  $('.container').removeClass('.move-right').addClass('move-left');
});
.container {
  margin-top: 20px;
  width: 10px; height: 10px;
  background-color: green;
}
.move-right {
  animation: move-right 10s linear;
}
.move-left {
  animation: move-left 10s linear;
}
@keyframes move-right {
  to {
    transform: translateX(500px);
  }
}
@keyframes move-left {
  to {
    transform: translateX(0);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="left">Left</button>
<button id="right">Right right first</button>
<div class="container"></div>

http://codepen.io/Deka87/pen/GWVbjv

This current solution does not work as expected, likely due to the need to save the current translate position resulting in unexpected behavior when resizing the page. Is there a more reliable alternative? (Perhaps using `animation-direction`).

Answer №1

One approach is to use the initial value as a starter for the left animation, and also apply forwards to maintain the final state of the animation:

$('#right').click(function() {
  $('.container').removeClass('move-left').addClass('move-right');
});
$('#left').click(function() {
  $('.container').removeClass('move-right').addClass('move-left');
});
.container {
  margin-top: 20px;
  width: 10px; height: 10px;
  background-color: green;
}
.move-right {
  animation: move-right 2s linear forwards;
}
.move-left {
  animation: move-left 2s linear forwards;
}
@keyframes move-right {
  to {
    transform: translateX(100px);
  }
}
@keyframes move-left {
  from {
    transform: translateX(100px);
  },
  to {
    transform: translateX(0);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="left">Left</button>
<button id="right">Right right first</button>
<div class="container"></div>


Bonus

If your aim is simply to move the element that way, you might prefer using transition. Check out the following snippet below, which will enable you to utilize the buttons when the transition is occurring in your initial code. If you press the buttons, they will smoothly transition rather than abruptly changing positions.

$('button').click(function() {
  if($(this).attr('id')=="right") {
    $('.container').addClass('move')
  } else {
    $('.container').removeClass('move')
  }
});
.container {
  margin-top: 20px;
  width: 10px; height: 10px;
  background-color: green;
  transition:transform 2s linear;
}
.move {
  transform: translateX(100px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="left">Left</button>
<button id="right">Right right first</button>
<div class="container"></div>


Jquery animate()

$('button').click(function() {
  if($(this).attr('id')=="right") {
    $('.container').stop().animate({'left':'200px'},2000)
  } else if($(this).attr('id')=="left") {
    $('.container').stop().animate({'left':'0'},2000)
  } else {
    $('.container').stop()
  }
});
.container {
  position:relative;
  margin-top: 20px;
  width: 10px; height: 10px;
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="left">Left</button>
<button id="pause">Pause</button>
<button id="right">Right right first</button>
<div class="container"></div>

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

Find the closest multiple of 3 for the given number

In our coding project, we have encountered a scenario where the input must be divisible by 3. For instance, if someone enters the number 9, everything works perfectly as expected. However, when a user inputs the number 7, the program returns the result wit ...

Concluding the use of angular-bootstrap-datetimepicker when selecting a date

I am currently utilizing the UI Bootstrap drop-down component to display the angular-bootstrap-datetimepicker calendar upon clicking. Although it works well for the most part, I have encountered an issue where the calendar block does not close when clicked ...

How can I send parameters to an HTML file using Node.js?

In my current code res.sendfile('./home.html',{user:req.user}), I need to figure out a way to access the user parameter directly in the HTML file without relying on a template engine. Can anyone suggest how this can be achieved? ...

Having a bottom border only on input fields appears strange when viewed on a mobile device

When trying to achieve a bottom border on mobile, I encountered an unexpected issue where a strange line appeared instead in the browser. Here is an image of the problem: https://i.sstatic.net/PqEOF.jpg I expected to see a straight line as intended (it w ...

What is the reason behind negative numbers appearing as "5-" rather than "-5" in the basic calculator coded using HTML and JavaScript?

As I am practicing my coding skills, I encountered an interesting issue. Any operation that results in a negative number displays as wrong, but when using console.logs it shows the correct result. Can someone explain why this is happening? <!DOCTYPE h ...

Discover the steps to trigger a Bootstrap popup modal when clicking on an anchor link using Angular

I have an Angular application and I would like to display a Bootstrap popup modal when the user clicks on a link in the footer. Here is the Bootstrap modal code: <button type="button" class="btn btn-primary" data-toggle="modal&q ...

The HTML checkbox is initialized as checked when the page loads

Is there a way to set the checkbox as unchecked in HTML? I have tried multiple ways, but it always loads as checked <input id="chkBox" checked type="checkbox" /> <input id="chkBox" checked=false type="checkbox" /> <input id="chkBox" checked ...

Assigning multiple properties to objects in Javascript

Can you show me a quicker way to do this? object.position.x = position.x object.position.y = position.y object.position.z = position.z object.rotation.x = rotation.x object.rotation.y = rotation.y object.rotation.z = rotation.z Your assistance is greatly ...

Vuetify vueJS dialog with elevated design

Is there a way to completely remove the elevation of a v-dialog so that it has no shadow at all? The elevation property in the v-dialog itself and using the class as Class = "elevation-0" have not worked for me. Here is the link to the component ...

Incorporating JavaScript timeout alerts into a dynamic webpage with a running AJAX task

Operating as a single page AJAX application, my system performs a recursive data gathering operation in the background. While the data is being collected, users have the ability to engage with the page even though the database could potentially be quite la ...

Integrating Jquery with React Portals for dynamic functionality

I'm currently working on a React project that involves using React Portals. While I've successfully loaded the portal in a new window with data displayed in a table, I'm facing an issue with adding the Jquery DataTable library to the table w ...

Having trouble removing or adding a class to an HTML element?

I have a collection of three colored buttons. My goal is to allow users to select one button at a time, triggering it to be highlighted while the others are unselected. Each button corresponds to an object with a property called isSelected that can be set ...

Importing a newly harvested array from a .js file (array that has been exported)

I followed this procedure with assistance from T.J to resolve my issue To address the problem, I made changes to my process. The steps I took are as follows: I switched from exporting an array through a JS file to saving a JSON file instead. Using the .g ...

Unable to launch React Native project on emulator now

Something seems off with my App as it won't start up on my AS Emulator. Everything was running smoothly yesterday, but today it's not working - possibly due to me moving the npm and npm-cache folders, although they are configured correctly with n ...

Implementing ES6 Angular directives with two-way isolated binding

I'm really struggling to understand how isolating scopes function in my code. Interestingly, everything seems to work fine when I remove the scope part of the directive. Can someone please shed some light on what I might be overlooking? export func ...

Tips on establishing validators for deeply nested form controls within form groups in Angular 6 reactive forms

In my form array (experiencesArray), I have nested nested nested form controls (companyname), as shown below. this.personalFormGroup = this._formBuilder.group({ professionalInfo: this._formBuilder.group({ totalexpyears: ['', Validators.req ...

Acquire dynamically loaded HTML content using Ajax within a WebView on an Android

I have been attempting to extract the content of a web page on an Android platform. Despite trying JSoup, I faced a limitation with ajax support. As an alternative, I am endeavoring to embed the URL within a hidden web view and retrieve the HTML in the on ...

Tips for effectively creating a fresh array of objects by extracting distinct values from arrays of child elements within a collection of parent objects

We have a requirement to extract data from objects structured like this: [ { "first": { "children" : [{ "name": "abc", "detail":"123"}, { "name": "def", "detail":"456"} ] }}, { "second": { "children" : [{ ...

Filtering through values stored in the .data() object

UPDATE: Don't forget to check out the jsfiddle for this question! I am working with an SVG image that contains various paths and shapes, each enclosed in a <g> element with its own unique id. For the sake of simplicity, I have included only two ...

When utilizing the Mongodb findOne function, it may not return any results or could

Being new to Node.js/Mongo, I might be completely off-base here. I have a local db.js file that utilizes callbacks to provide me with information on a MongoDB collection object. The object is valid and when I call find() from my callback, it returns a cur ...