Thumbnails leading to modal images, with AVIF falling back to JPG

66 Views Asked by At

I've an old web page with a few dozen images, mostly:

 <a href="pix/name1big.jpg"><img src="pix/name1small.jpg"></a>

so thumbnails are loaded first, then users can click on most (not all) images to see high-res versions. N.B. it's not a lightbox - the images are less important than the text, and are scattered throughout.

It works, but I want to modernize it by (a) making the high-res versions modal; (b) making these modal versions AVIF, falling back to JPG. I've found lots of suggestions for modal display, but none showing how to pass a <picture> element with AVIF and JPG options to the modal window.

My idea is something like what's shown below, but it's only pseudocode at this stage... I'm getting bogged down in syntax whereas I don't even know if my overall approach is correct. So general suggestions are welcome at this stage - I don't want anyone to code it for me, just some pointers. I'll happily fix the details of the code and debug later.

<img src="pix/name1small.jpg" onClick=makeModal(this)>
...
<img src="pix/name2small.jpg" onClick=makeModal(this)>
...
<div id="modalcontainer" class="..." style="...">
 <picture id="hirespic"></picture>
</div>

<script>
function makeModal(element) {
 hiresname=URL(element.src).pathname.replace("small","big");
 hiresname=URL(element.src).pathname.replace(".jpg","");
 document.getElementById("hirespic").content=<source srcset=hiresname+".avif" type="image/avif"> <img src=hiresname+".jpg">
 modalcontainer.style.display = "block";
}
</script>
1

There are 1 best solutions below

0
On

Having waited in vain for input here and two other places, I finally tried ChatGPT and it soon guided me to a workable solution, shared here in case it helps others. It's a one-off solution but could easily be adapted.

...
<script>
  function openModal(avifSrc, jpgSrc) {
    document.getElementById("modalPic1").srcset = avifSrc;
    document.getElementById("modalPic2").src = jpgSrc;
    document.getElementById("myModal").style.display = "block";
}

  function closeModal() {
    document.getElementById("myModal").style.display = "none";
  }
</script>

</head>
<body>

<p><img src="low-res.jpg" onclick="openModal('high-res.avif', 'high-res.jpg')"></p>

<div id="myModal" class="modal">
  <span class="close" onclick="closeModal()">×</span>
  <picture class="modal-content">
    <source srcset="" type="image/avif" id="modalPic1" class="modal-image">
    <img src="" type="image/jpeg" id="modalPic2" class="modal-image">
  </picture>
</div>
...