Modal Images For Your Hugo Website

ยท 345 words ยท 2 minute read
Photo
Photo by me
Learn how to add modal images to your hugo website

Hugo is a great tool for building static websites. In fact, this site was also built with it. However, it does not offer modal images out of the box. But with the following steps, it is easy to add this functionality to your website. The example code uses bulma css, but it shouldn’t be too hard to use custom css styling.

Add custom js code ๐Ÿ”—

Create the following js file at /static/js/modal.js:

function openModal(imageId) {
    const modal = document.getElementById("uphillModal");
    if (modal === null) {
        return
    }
    // Get the original image element and use it inside the modal
    const img = document.getElementById(imageId);
    const modalImg = document.getElementById("modalImg");
    const captionText = document.getElementById("caption");
    
    // Display modal
    modal.style.display = "block";
    modalImg.src = img.src;
    captionText.innerHTML = img.alt;

    // The element that closes the modal
    const close = document.getElementsByClassName("modal-close")[0];
    // When the user clicks on (x) button, close modal.
    close.onclick = function () {
        modal.style.display = "none";
    }
    // When the user hits ESC, close modal as well.
    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape') {
            modal.style.display = "none";
        }
    })
}

Depending on which theme you use, you can simply add custom js files to your hugo configuration file:

  customJS:
      - js/modal.js

Alternatively, you should be able to add it to your HTML files like so:

{{ range .Site.Params.customJS }}
    <link rel="stylesheet" href="{{ $.Site.BaseURL }}/{{ . }}">
{{ end }}

Add modal partial html file ๐Ÿ”—

Create the following HTML file at /layouts/partials/modal.html:

<div class="modal" id="uphillModal">
    <div class="modal-background"></div>
    <div class="modal-content">
        <p class="image is-4by3">
            <img src="" alt="" id="modalImg">
        </p>
        <div id="caption">
        </div>
    </div>
    <button class="modal-close is-large" aria-label="close"></button>
</div>

Adapt markup image rendering ๐Ÿ”—

Adapt the render-image.html at /layouts/_default/_markup/. Note: This will affect all images occurring in your articles.

<p class="markdown-image">
  <img class="modal-image" id="{{ first 6 (shuffle (seq 1 500)) }}" src="{{ .Destination | safeURL }}" onclick="openModal(this.id)" alt="{{ .Text }}" {{ with .Title }} title="{{ . }}"{{ end }} />
</p>

Add partial HTML to template ๐Ÿ”—

Finally, you can add the partial modal into your templates, where you want to use the modal image:

...
<div>
    {{ partial "modal.html" . }}
</div>
...