Move a pair of divs at the same time using CSS animations

I am working on creating a dynamic sliding animation that transitions between two different divs. Here is the current progress of my code:

var current = $('#blue');
var other = $('#red');

function slider($elem_in, $elem_out) {
  $elem_in.show();
  // reset the animations
  $elem_in.css('animation', '');
  $elem_out.css('animation', '');
  // remove the previous event handler
  $elem_in.off('animationend');
  // make the elem_out slide out
  $elem_out.css('animation', 'slideLeftOut 1s ease');
  $elem_out.on('animationend', function() {
    $elem_in.css('animation', 'slideLeftIn 1s ease');
    $elem_out.hide();
  });
}

$('#container').on('click', function() {
  slider(other, current);
  // swap the values of current and other variables
  other = [current, current = other][0];
})
#container {
  width: 100px;
  height: 100px;
  overflow: hidden;
  border: 1px solid black;
}

#container div {
  height: 100%;
  width: 100%;
}

#red {
  background: red;
}

#blue {
  background: blue;
}


/* define slide to the left in animation */

@keyframes slideLeftIn {
  0% {
    transform: translateX(150%);
  }
  100% {
    transform: translateX(0%);
  }
}


/* define slide to the left out animation */

@keyframes slideLeftOut {
  0% {
    transform: translateX(0%);
  }
  100% {
    transform: translateX(-150%);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
  <div id="blue"></div>
  <div id="red"></div>
</div>

There are two issues I am currently trying to address:

  1. When I click and current is set as $('#red'), it switches to blue before animating. However, if current is assigned as $('blue'), the animation functions correctly.

  2. Is there a way to eliminate the blank space between the sliding divs? I attempted to move the

    $elem_in.css('animation', 'slideLeftIn 1s ease');
    outside of the event handler, but this caused the animation to not play at all.


I have come across similar questions like this one. However, the solutions provided involve absolute positioning, whereas I am aiming to achieve my desired animation using CSS transitions instead.

Answer №1

The issue with problem number 1 is regarding the positioning of the element. Once the second element slides, there is no other element to slide in from the right. To fix this, simply take the first animated div and append it at the end.

$elem_out.hide().remove().appendTo("#container");

Furthermore, you can eliminate the need for switching logic by directly referencing the two elements inside the slider() function like so:

$('#container').on('click', function() {
  slider($(this).children().eq(1),$(this).children().eq(0) )
})

Check out this jsfiddle link for a demo.

Unfortunately, I am unable to assist with problem 2 at this moment.

Answer №2

My curiosity led me to experiment with creating a version that involves a wrapper and a container with two elements floating left inside it. Instead of animating the individual elements, I decided to animate the container itself.

function slider(container) {
  container.css('animation', 'slideLeft 1s ease')
    .on('animationend', function() {
      console.log("swap!");
      container.off('animationend') // remove handler
        .css('animation', '') // reset css
        .children().eq(0).remove().appendTo(container); // swap
    });
}

$('#container').on('click', function() {
  slider($(this));
})

https://jsfiddle.net/ofc4w7dy/

Feel free to check out my CSS and comments. You can also try animating the elements separately if you'd like.

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 reason the link:visited attribute is not functioning properly for a specific page link?

I have set up links between different pages on my website. What I want is for the link that a visitor clicks on to change color once they've visited that page. Unfortunately, this feature isn't working for me and I'm not sure why. Here&apo ...

CodeIgniter's Comparison Feature: Like vs. Unlike

I'm looking to integrate the like and unlike functionality into a CodeIgniter project. I have successfully implemented it in normal PHP with the code below, but for some reason, it's not working in CodeIgniter. Below is the structure of my databa ...

Tips for repairing my Bookmark local-storage tool

My Bookmark Service, which stores result items with a JSON structure, is experiencing issues. It seems that the problem lies in the array not functioning properly with the local storage feature. I have attempted to use JSON.stringify on my items. va ...

Set default date input in Ionic to be today's date

I'm currently developing a project using Ionic framework and I need to set a default date (which is today's date) on an input field. My code works perfectly when the input type is set to text, but it doesn't work if I specify the type as da ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

How to iterate through properties declared in an Interface in Angular 12?

Before Angular 12, this functioned properly: export interface Content { categories: string[] concepts: Topic[] formulas: Topic[] guides: Topic[] } //this.content is of type Content ['formulas', 'concepts'].forEach(c =&g ...

Achieving repetitive progress bar filling determined by the variable's value

JSFiddle Here's a code snippet for an HTML progress bar that fills up when the "battle" button is clicked. I'm trying to assign a value to a variable so that the progress bar fills up and battles the monster multiple times based on that value. ...

JS: what is the purpose of utilizing Symbols when they cannot be accessed?

I'm a bit confused about the role of Symbols if they can't be easily accessed. I understand that you can create one using a key with for and then retrieve it with keyFor. let keySymbol = Symbol.for("XXX"); console.log(Symbol.keyFor(key ...

What could be causing the slight pause in my CSS3 animation at each keyframe percentage range?

I'm currently working on an animation for a sailing ship, but I'm encountering some issues with its smoothness. Whenever I make changes in the @keyframes, the animation stops abruptly. The movement involves using transform:rotate(-5deg) and then ...

The disappearance of node_modules results in the failure to install any dependencies for a React application, causing an error to be thrown

I've been struggling to get a react app installed, but every time I try, I encounter the following error and the entire node_modules folder disappears. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! Found ...

Using the parseInt method, you can easily combine integers and strings to perform addition and string concatenation simultaneously

Here is the code snippet I am working with: if (ev.data.type === "height") { if (ev.data.form === src) { setHeight(ev.data.message + "px"); } } Currently, the default height being added is 1900px. I would like to increase it by ...

Issue with user identity in signalR-1.0.0-rc2 causing functionality to fail

While attempting to work with SignalR 1.0.0 RC2, I noticed significant changes from version 0.5.3. One issue I encountered is that "Context.User.Identity.Name" now returns a null value. I am unsure if this is still the correct way to access the Windows use ...

What is the best way to establish a global database connection in express 4 router using express.Router()?

Is there a way to pass a global variable in Node.js from a file to a module? I have been attempting to do so with a 'db' variable that represents a MongoDB connection. I tried copying the content of my file for the connections, but it didn't ...

Tips for inserting values into a JSON array using Node.js and Mongoose

Currently, I am working with Mongoose to add values from HTML and then save them to a database using Mongoose. However, I am encountering an issue when trying to add the value from req.body.chapter into the array in HTML. The route looks like this: con ...

Filter Observable based on object array property

I am trying to filter an Observable and only keep the stream that has a specific property value in an array of objects inside it. For example, consider this Observable: const observable = of({name: 'agency', year: '2010', job: [ ...

Tips for automatically expanding all nodes with children when the page loads in the Wix Angular tree control

Is there a way to automatically expand all nodes with children when the page loads in an Angular tree control? The tree control is full of useful features, but this specific functionality seems to be missing. It does have a property for expanded nodes. Do ...

Changing values in two jQuery forms on a single page

I have a table listing all my users. The last td element in each row contains a form, which is either for opening or closing the user's account based on their current status. I am utilizing the jQuery AJAX form plugin from http://malsup.com/jquery/for ...

Transfer the AngularJS variable's value either directly to JSP or using an intermediary JS variable

On my .jsp web page, I am facing an issue with an AngularJS nested dropdown menu: <div ng-controller="AlgoController"> <select ng-model="myModel" ng-options="model.name group by model.shade for model in models"></select> Although I can ...

Steps to configure useState to manage data within an object

Having trouble setting an object with useState in my code. Despite my effort, I am only getting the initial value for the object named setWishlist. Can someone spot what mistake I am making? const CenterModal = props => { const [modalData, setModalDa ...

Converting object keys to strings based on their corresponding values

Hi there, I am currently working with a React component that has an object in its state called modals, with boolean values indicating whether certain modals are active or not. What I want to achieve is extracting the active modals based on the true values ...