I made a quick update to my photo gallery today. Previously, photos were displayed top to bottom from newest to oldest. I didn’t really like that user experience for two reasons.

  • As I add more images over time, older photos will get pushed further down the page. This means older photos may get less views.
  • I tend to go through phases in my photography. For example, I may spend an entire month only shooting black and white. Displaying 20-30 black and white images in a row (due to the default sort order) attracts unnecessary attention and doesn’t look good.

To fix this, I decided to randomize the image order in my photo gallery.

The first method I tried involved shuffling the actual HTML structure during site generation in Hugo by adding a shuffle function into my range code.

{{ range (shuffle (where .Site.RegularPages "Type" "in" (slice "photo"))) }}

This technically works fine, but then I decided that I wanted the image order to be different for every page reload. To do this, I got rid of the shuffle function and added some JavaScript instead.

$(".photo-container").html($(".photo-container .photo-item").sort(function(){return Math.random()-.5}));

The code above randomizes the .photo-item divs in my .photo-container div. To see this solution in action, check out my photo gallery!