Skip to content
Advertisement

How to Swap Two Divs With Animation

I have a project where I want a div to appear as a large box and three more to appear underneath as smaller boxes and when you click a smaller box, it switches sizes and places with the large box using css transitions to make the movement and size change smooth. Right now I’m attempting to use jQuery and the positioning is not working at all. Here’s an example of what I have so far:

https://jsfiddle.net/v3pmhawj/1/

$(function () {
    let { left: x1, top: y1 } = $('.full-size-card').offset()
    
    $('.inactive-sheets .card').on('click', function() {
        let { left: x2, top: y2 } = $(this).offset()
        
        let curr = $('.full-size-card')
        let diffX = x2 - x1
        let diffY = y2 - y1
        
        $(this).css({
            left: -diffX,
            top: -diffY
        })
        $(this).addClass('full-size-card')
        
        curr.css({
            left: diffX,
            top: diffY
        })
        curr.removeClass('full-size-card')
    })
})

If anyone has suggestions on ways that involve other libraries or other techniques, I’m all ears. I’d like to be able to move the divs around in the DOM as well but as far as I can tell, you can’t css-transition them if you do that since the only way (I know of) is to delete and re-add a copy of the element where you want it in the DOM.

Advertisement

Answer

You can create animation effect using transitions only. To achieve this you will have to define width and height of your containers as well as top and left position of bottom elements.

On click, you just have to exchange classes of element that will become small and of element that will become large.

Here is fiddle of an example: https://jsfiddle.net/fkd3ybwx/210/

HTML

<div class="card-container">
  <div class="card large">A</div>
  <div class="card small">B</div>
  <div class="card small">C</div>
  <div class="card small">D</div>
</div>

CSS

.card-container {
  position: relative;
}

.card {
  transition: all ease 1s;
  position: absolute;
  font-size: 24px;
  border: white 4px solid;
  box-sizing: border-box;
  cursor: pointer;
}

.small {
  width: 100px;
  height: 100px;
  background: blue;
  left: 0;
  top: 300px;
}

.small ~ .small {
  left: 100px;
  background: green;
}

.small ~ .small ~ .small {
  left: 200px;
  background: yellow;
}

.large {
  width: 300px;
  height: 300px;
  background: red;
  left: 0px;
  top: 0px;
}

JavaScript

const smallCards = document.querySelectorAll('.card');

smallCards.forEach((smallCard) => {
    smallCard.addEventListener('click', (event) => {
    const largeCard = document.querySelector('.large');
    
    largeCard.className = "card small";
    event.target.className = "card large";
  });
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement