This is from an early attempt on JS Fiddle.

By setting the grid container to grid-auto-flow: column; and grid-auto-columns: 1fr; you can add an extra images and the grid will adapt.

The number in JS uses img.length - the length of the node list of images. Also there is no back button and it's not as responsive as it could be.

back