Jump to content

Image Order from Newest to Oldest in Masonry Grid Image Gallery

Recommended Posts

@sian75 The following JS should do the trick as long as you place it in the Header using Code Injection. This will allow the script to run and re-order the elements before the site runs Squarespace's JS code that handles the masonry layout. 

JavaScript

(function(){

  // Value of the "data-section-id" attribute of the element with a class of "gallery-masonry"
  const SECTION_ID = '65b13fd4e94d515c51c1e3cb';

  /*********************************************************************************
   * DO NOT EDIT BELOW UNLESS YOU KNOW WHAT YOU'RE DOING
  *********************************************************************************/
  if(document.readyState == 'complete') {
    reverseOrderOfGalleryItems();
  } else {
    window.addEventListener('DOMContentLoaded', reverseOrderOfGalleryItems);
  }

  function reverseOrderOfGalleryItems() {
    // Get the parent element that contains the <figure> elements
    const gallery = document.querySelector(`.gallery-masonry[data-section-id="${SECTION_ID}"] .gallery-masonry-wrapper`);

    // Get a NodeList of all <figure> elements within the parent element
    const figureElements = gallery.querySelectorAll('figure');

    // Convert the NodeList to an array and reverse it
    const reversedFigures = Array.from(figureElements).reverse();

    // Remove existing <figure> elements from the parent
    figureElements.forEach(figure => figure.remove());

    // Append the reversed <figure> elements back to the parent
    reversedFigures.forEach(figure => gallery.appendChild(figure));
  }
  
})()

Remember to place the JavaScript code in between <script> tags, e.g.

<script>
  // Add JS code here
</script>

 

Full stack developer who loves helping people out with anything web related. If you'd like to support me, buy me a coffee!

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.