Help randomizing an image on each site refresh

Hi there,

I’m trying to add to my Hugo site a section which will show a randomized photo from a specific folder each time you refresh the page and/or click the current image.

I know about the readDir function and I plan to utilize it reading my folder with random images and then fetching the filenames. The step where I’m stuck is how to assign the filename to the <img> tag on each site refresh. I think the best approach for this dynamic behavior is passing the readDir output to as JS variable and then fetching the <img> tag using the getElementById() js function and then passing a random member out of the readDir output. The only thing I don’t know is how to mesh hugo functions with JS variables. Also I’m open for suggestions if there is a better way of doing this.

This is the shortcode part I got for now:

{{ $dir := "static/randomImages" }}
{{ $images := readDir $dir | shuffle }}

Hugo is a static site generator. It creates hardcoded html. What you want to do is not possible with Hugo because it isn’t a dynamic site that is built on every visit. You might be able to do it with JavaScript but that’s not the scope here.

Here’s a an example:

git clone --single-branch -b hugo-forum-topic-40215 https://github.com/jmooring/hugo-testing hugo-forum-topic-40215
cd hugo-forum-topic-40215
hugo server

A few notes:

  • Storing the images somewhere in the assets directory is more flexible, allowing you to access each image as a global resource. That makes image manipulation (resizing, setting a target format, etc.) much simpler.
  • Using a data-foo attribute on the img element seemed like the easiest way to pass the array of images to the JS.
  • Session storage was necessary to ensure that the next random image will be different than the current random image.
  • My JS skills are rudimentary at best, so I’m sure this could use some improvement.
5 Likes