I have two images on the page, one at the first row and one at the second row, to make it look like the images are scattered. I added a button which, when pressed, the images will go to one row only, showing that it is arranged.
I took inspiration from this website: https://www.phsofia.com/photoset/karina. I tried to copy the "change view" button
My code currently:
var btn_arrange = document.getElementById("btn-gallery-arrange");
var gallery = document.getElementById("gallery");
var gallery_img = gallery.querySelectorAll("img");
var img_Array = Array.from(gallery_img);
btn_arrange.addEventListener("click",function(){
img_Array.forEach(function(el){
el.style.gridRow = "1";
el.style.gridColumn = "span 1";
});
},false);
#one{
grid-row: 1;
grid-column: 2/3;
transition: 1s;
}
#two{
grid-row: 2;
grid-column: 3/5;
transition: 1s;
}
#gallery{
display: grid;
transition: 1s;
}
<button id="btn-gallery-arrange">arrange!</button>
<div id="gallery" class="display">
<img id="one" class="one" src="https://picsum.photos/200/300" alt="">
<br>
<img id="two" class="two" src="https://picsum.photos/200/300" alt="">
Problem: The Image element teleports to new place after clicking button.
Tried: I tried adding a transition
property to the images, expecting them to go to their new places smoothly.
2
Answers
You cannot do this with
grid
The CSS transition property does not work with
grid
. Let’s say you try to change the row an element is in, from row 2 to row 1. You can’t have an element that is in row 1.5; or in row 1.9 or row 1.0001. There’s no such thing as a partial row – the image is either in row 1 or row 2.So when your JavaScript changes the grid position of an element, it cannot be smoothly animated into its new position. Instead, you’ll have to find another way.
Instead
You’ll need to find another way to scatter the images. One way would be to CSS transforms. You can place the images in their final positions on the page, and then add a CSS transform to scatter them. On the button click, you remove the transform.
CSS transforms are fully animatable.
I developed this site) To achieve this effect, the easiest way is to use the GSAP animation library and a plugin for this library called GSAP Flip. Here is a case with a similar animation where you can study this in more detail: https://tympanus.net/codrops/2023/07/27/grid-flow-animation/