JavaScript click-to-zoom function
Simple JavaScript function to enable click-to-zoom on all images on the page. Written as a solution for WISYWIG site editors without this feature and/or pages that have high-res images squashed to small size.<script defer> function viewFullscreenImage(img_src) { // Semi-transparent background for the fullscreen image let fsi_bg = document.createElement('div'); fsi_bg.style = 'z-index: 99999; background-color: #000000c0; position: fixed; left: 0; top: 0; width: 100vw; height: 100vh;'; fsi_bg.onclick = function() { fsi_bg.remove(); }; // Close when user clicks anywhere on the fullscreen image // Image let fsi_img = document.createElement('img'); fsi_img.src = img_src; fsi_img.style = 'position: fixed; box-sizing: border-box; max-width: 100vw; max-height: 100vh; margin: auto; top: 0; bottom: 0; left:0; right: 0; padding: 16px'; // Close button let fsi_close = document.createElement('button'); fsi_close.textContent = '×'; fsi_close.style = 'cursor: pointer; position: fixed; top:0; right: 0; margin: 4px; padding: 0.1em 0.4em; border: 0; background-color: #000000; color: #ffffff; font-size: 32px' fsi_close.onclick = function() { fsi_bg.remove(); }; // Compose the fullscreen view fsi_bg.append(fsi_img); fsi_bg.append(fsi_close); document.querySelector('body').append(fsi_bg); } const imgs = document.querySelectorAll('div.wsite-image img'); // Selector for which img tags should have this ability for (const img of imgs) { img.onclick = function() { viewFullscreenImage(img.src) }; } </script>