CSS simultaneous transition on multiple elements

There are a number of improvements that can be made to your code that will reduce duplication, avoid complications of interacting with the live HTMLCollection that getElementsByClassName returns, allow you to avoid using inline onclick assignments, and will cause the transition to only take 1 second.

The example below implements a single grow() function which is called by listeners attached to each box. The listeners are added by iterating over the NodeList returned by querying the DOM with .querySelectorAll('.box') and calling addEventListener() on each element.

In the CSS we declare classes for each state we want our boxes to be able to have – in this case flex-grow: 0 and flex-grow:4. Then in our grow() function we simply add or remove these styles as necessary based on which box was clicked.

function grow(e){
      // if the clicked box already has class 'flexgrow4' return
      if (e.currentTarget.classList.contains('flexgrow4')) return;
      
      // otherwise find the element in the flexbox container that has
      // class 'flexgrow4' and replace it with 'flexgrow0'
      const lastActive = flexbox.querySelector('.flexgrow4');
      if (lastActive) lastActive.classList.replace('flexgrow4', 'flexgrow0');
      
      // finally, replace 'flexgrow0' with 'flexgrow4' on the clicked box
      e.currentTarget.classList.replace('flexgrow0', 'flexgrow4');
}

const flexbox = document.querySelector('.flexbox');
const boxes = document.querySelectorAll('.box')

boxes.forEach(box => box.addEventListener("click", grow, false));
.flexbox {
    display: flex;
    width: 100vw;
    justify-content: center;
}

.flexbox div {
    border: 1px #ccc solid;
    border-radius: 10px;
    width: 100px;
    height: 250px;
    padding: 10px;
    margin: 2px 10px;
    transition: all 1s linear 0s;
}

.flexgrow0 {
  flex-grow: 1;
}

.flexgrow4 {
  flex-grow: 4;
  background-color:tomato;
}
<div class="flexbox">
            <div class="box flexgrow0">
                <h3>Box 1</h3>
                <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore</p>
            </div>
            <div class="box flexgrow0">
                <h3>Box 2</h3>
                <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore</p>
            </div>
            <div class="box flexgrow0">
                <h3>Box 3</h3>
                <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore</p>
            </div>
        </div>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top