Skip to content
Advertisement

Transition on multiple elements at the same time using JavaScript

Cheers! I’m having an issue debugging certain behavior that occurs mostly in the Chrome browser. Here is the simplified example: https://jsfiddle.net/pd3xb2uo/

The objective is to transition multiple elements via JS code at the same time. In the example when you click on the button, items are moved to the left using translate3d added via JS. It works fine, but there are some caveats:

  1. There is a small gap appearing between the items most of the time
  2. Sometimes when you click faster on the button there is a large gap appearing between the items.

Here are the screenshots of both cases:

small gap

large gap

Any help or ideas on why it is happening would be highly appreciated:) It looks like there is a few milliseconds delay before the style attribute is updated on certain elements, but I have no idea why:/

Advertisement

Answer

The problem occurs because you are transitioning 100 elements at the same time and because of half-pixel transitions.

If you know how wide and how many elements you have, then you can do it like so:

 const container = document.querySelector('.container-inner');
 for (let i = 1; i < 100; i++) {
   const div = document.createElement('div');
   div.classList.add('element');
   div.textContent = `Element ${i}`;
   container.appendChild(div);
 }
 let transition = 0;
 document.querySelector('button').addEventListener('click', () => {
   transition -= 100;
   container.style.transform = `translateX(${transition}px)`;
 });
.container{
  width: 100%;
  overflow: hidden;
}
.container-inner{
  display: flex;
  flex-direction: row;
  transition: transform .3s;
}
.element {
  width: 100px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2rem;
  text-align: center;
  transition: transform .3s;
  background-color: #A67583;
}
<button>Move</button>
<div class="container">
  <div class="container-inner"></div>
</div>

Now only one element gets transitioned and it is working smoothly.

Advertisement