Different techniques for using percentages in CSS transformations to create dynamic animations for DOM element translations

I have 14 objects positioned across the dom that I need to animate using the translate property. Currently, I am using transform: translate(x%, y%) for each object, requiring me to calculate the translation amount and apply a CSS style individually. This method becomes complex as the percentage translation is relative to the object's dimensions, meaning adjustments are needed if the object size changes.

.container {
  position: relative;
  width: 40%;
  padding-bottom: 40%;
  height: 0;
  background: #cdc;
}

.seats {
  position: absolute;
  width: 100%;
  height: 100%;
}

.seats .seat {
  position: absolute;
  width: 20%;
  height: 20%;
}

.seat.one {
  bottom: 0%;
  left: 50%;
}

.seat.two {
  bottom: 50%;
  left: 0%;
}

.seat.three {
  bottom: 50%;
  left: 80%;
}

.cards {
  position: absolute;
  height: 100%;
  width: 100%;
}

.cards .dealer {
  position: absolute;
  bottom: 90%;
  left: 50%;
}
<div class='container'>
  <div class="cards">
    <div class="dealer">
      Dealer
    </div>
  </div>
  <div class="seats">
  
  <div class="seat one">
    <div class="hand">
    Hand 1
    </div>
  </div>
  <div class="seat two">
    <div class="hand">
    Hand 2
    </div>
  </div>
  <div class="seat three">
    <div class="hand">
      Hand 3
    </div>
  </div>
  </div>
</div>

I am looking for a more efficient way to animate the translations of the elements without needing so many custom calculations and tweaks. Specifically, I want to smoothly move Hand 1/2/3 towards Dealer, with the animation reversible as well.

The current translation method does not work properly when resizing the container element. Is there an alternative approach that simplifies the process of translating DOM elements?

Answer №1

To easily control the display of elements, you can incorporate a CSS class and switch it on or off as required.

const toggle = document.getElementById('toggle');
const seats = document.querySelectorAll('.seat');

toggle.addEventListener('click', e => {
  seats.forEach(seat => {
    seat.classList.toggle('not-dealt');
  });
});
.container {
  position: relative;
  width: 40vmax;
  padding-bottom: 40vmax;
  height: 0;
  background: #cdc;
}

.seats {
  position: absolute;
  width: 100%;
  height: 100%;
}

.seat {
  position: absolute;
  background: #d99;
  transition: all 2s;
  white-space: nowrap;
}

.one {
  top: 100%;
  left: 50%;
  transform: translate(-50%, -100%);
}

.two {
  top: 50%;
  left: 0%;
  transform: translate(0, -50%);
}

.three {
  top: 50%;
  left: 100%;
  transform: translate(-100%, -50%);
}

.not-dealt {
  top: 0;
  left: 50%;
  transform: translate(-50%, 50%);
}

.cards {
  position: absolute;
  height: 100%;
  width: 100%;
}

.dealer {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 50%);
}
<div class="container">
  <div class="cards">
    <div class="dealer">
      Dealer
    </div>
  </div>

  <div class="seats">
    <div class="seat one">
      <div class="hand">
        Hand 1
      </div>
    </div>
    <div class="seat two">
      <div class="hand">
        Hand 2
      </div>
    </div>
    <div class="seat three">
      <div class="hand">
        Hand 3
      </div>
    </div>
  </div>
</div>

<button id="toggle">Toggle Cards</button>

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

Tips for managing media queries in HTML emails on Gmail

When sending out my website's responsive HTML emails, I utilize media queries to ensure optimal display. However, I have noticed a discrepancy in how Gmail/Inbox interprets the max-width parameter in the media query. Instead of referencing the HTML em ...

What is the best way to test the Express router catch branch in this specific scenario with Jest?

My current task involves working with a file containing two routes. The first route is located in routes/index.js const express = require('express') const router = express.Router() router.get('', (req, res, next) => { try { r ...

I am interested in scraping a webpage, how should I go about it?

Similar Questions: How to create a web crawler? Top techniques for parsing HTML I've always been curious about accomplishing a task like this. Although I do not own or manage the website (), the information I am interested in is publicly acce ...

Use jQuery.ajax() to submit data in separate rows of a table

At the moment, I have no issues submitting my form as long as it contains only one row in the table. However, when I add a second row, an error occurs and the submission fails. My goal is to be able to post the data from each table row separately with just ...

ajax is triggering the error handler

I am currently developing a web application and I am trying to send data from a PHP controller to JavaScript. After conducting some research, it seems that the most efficient way to accomplish this is by utilizing Ajax and Json. However, I am encountering ...

Create a CSS border that resembles the one used in Google's signup form

lies a curious inquiry: what unique border style is in play here? It rests slightly raised against the backdrop, creating an intriguing visual effect. After combing through various sources online, the answer still eludes me. Perhaps turning to Google' ...

An unexpected error occurred while parsing the JSON document: "unexpected token: '{'"

I'm facing an issue where I need to specify a URL in a JavaScript app that retrieves weather data from an API. The URL is constructed using a string and some variables. When I initially wrote the code below, I encountered the error message Missing { b ...

Timepicker Bootstrapping

I've been searching for a time picker widget that works well with Bootstrap styling. The jdewit widget has a great style, but unfortunately it comes with a lot of bugs. I'm on a tight deadline for my project and don't have the time to deal w ...

Ways to condense a text by using dots in the middle portion of it

How can I dynamically shorten the text within a container that varies in width? The goal is to replace the strings between the first and last words with dots so that it fits within the container. For example, Sydney - ... - Quito. It should only replace wh ...

Can an EJS variable be transferred to an Angular ng-repeat filter?

I am currently working on a profile page where I need to display a user's name in plain text using <%= user.local.name %>. This requires querying the database through Mongoose. My issue now is figuring out how to pass that value to an Angular ng ...

Utilizing child component HTTP responses within a parent component in Angular: a comprehensive guide

As a newcomer to Angular, I find myself struggling with http requests in my application. The issue arises when I have component A responsible for retrieving a list of IDs that need to be accessed by multiple other components. In component B, I attempted t ...

Implementing an Asynchronous Limited Queue in JavaScript/TypeScript with async/await

Trying to grasp the concept of async/await, I am faced with the following code snippet: class AsyncQueue<T> { queue = Array<T>() maxSize = 1 async enqueue(x: T) { if (this.queue.length > this.maxSize) { // B ...

Differences between JavaScript array manipulation using the split(" ") method and the spread operator

I'm currently attempting to determine if a given sentence is a palindrome, disregarding word breaks and punctuation. The code snippet that utilizes cStr.split(" ") DOES NOT achieve the desired outcome. Although it splits on whitespaces (&qu ...

Toggle a Vue.js method to display responses for a particular question

Currently, I am in the process of developing a simple toggle feature for a FAQ section. The idea is that when a user clicks on an icon associated with a specific question, only that question's answer should be displayed. Although the function is oper ...

Utilize JQuery's .append() method to insert a new element into the DOM and then trigger an "on click" event within

I am attempting to use the .append() method to add a new radio button, and then when I click on the new radio buttons, trigger a new function. However, I am having trouble achieving this with my current code: HTML: <label>Where should the photo be ...

Is it possible to remove strings within HTML elements?

{% for term in terms %} <div class="term term-count-{{loop.index}}"> <b>{{ term }}</b>: &nbsp;&nbsp; {{ terms[term] }} &nbsp;&nbsp; </div> {% endfor %} 'terms' is a dictionary w ...

JavaScript alert system

Seeking advice on a situation. Here's the scenario I'm facing: In a messaging platform, I have an array of users who are currently online. When a new user joins the chat, I want to notify the first user in the array. If there's no response w ...

How can I configure AngularJS intellisense in Visual Studio Code?

I've been customizing Visual Studio Code for better compatibility with our Angular 1.5 codebase at my workplace. Here's the progress I've made so far: Downloaded and installed TSD Ran the command tsd query -r -o -a install angular -s Added ...

Unable to retrieve JSON data from converting TXT using JavaScript, resulting in undefined output

After converting txt to JSON, I encountered an issue. const txt = JSON.stringify(`{ ErrorList: [{ 80: 'Prepared' }], Reference: [ { 'Rule Name': 'Missing 3', 'Rule ID': 1, 'Rule Des& ...

Tips for improving performance with ng-repeat directive?

I have encountered some performance issues while using socket.io with the ng-repeat directive in Angular. The application slows down significantly when receiving a large amount of data from the backend, making it impossible to interact with the app. What w ...