Displaying all the images from all of my articles

I’m trying to replicate that codepen but using php wordpress. Basically I want my blogpost images displaying in another div and it changes every time you select another menu.

Thanks for the help.
Here is my code:

I have noticed that $images = get_field('gallery'); stores the image of the latests post before its called. So I guess it has something to do with that. Now I wish I could just get all the images somewhere and apply them a data id corresponding to my articles. That is why I have a $counter = -1;.

Here is the complete code:

All it does from now, is just displaying the latests post’s images correctly, what I would like is that its able to detect which post i’m clicking and display the image corresponding.