Make Product Detail Image clickable to PDF in Squarespace

Description

  • click product detail image will open PDF

  • view demo – password: abc

#1. Install Code

#1.1. First, add a Code Block in Product Additional Info

Next, paste this code

<script>
(() => {
  const getSection = () => document.querySelector('section.product-detail-section');
  const getPdfUrl = (root) => {
    const a = root.querySelector('.ProductItem-additional a[href$=".pdf"], .ProductItem-additional a[href*=".pdf"]');
    return a ? a.href : '';
  };
  const markImages = (root) => {
    root.querySelectorAll('.product-gallery img.product-gallery-slides-item-image').forEach(img => {
      img.style.cursor = 'pointer';
      img.setAttribute('data-tp-pdf-click', '1');
    });
  };
  const bind = () => {
    const root = getSection();
    if (!root) return;
    const pdfUrl = getPdfUrl(root);
    if (!pdfUrl) return;
    markImages(root);
    const gallery = root.querySelector('.product-gallery');
    if (!gallery) return;
    if (gallery.getAttribute('data-tp-pdf-bound') === '1') return;
    gallery.setAttribute('data-tp-pdf-bound', '1');
    gallery.addEventListener('click', (e) => {
      const hit = e.target && e.target.closest
        ? e.target.closest('.product-gallery-slides-item-image, .product-gallery-slides-item, .product-gallery')
        : null;
      if (!hit) return;
      e.preventDefault();
      e.stopPropagation();
      window.open(pdfUrl, '_blank', 'noopener');
    }, true);
  };
  const boot = () => {
    bind();
    const root = getSection();
    if (!root) return;
    const mo = new MutationObserver(() => {
      bind();
      markImages(root);
    });
    mo.observe(root, { childList: true, subtree: true });
  };
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();
</script>

#1.2. Next, add a Text Block > Enter PDF link

#2. Customize

#2.1. To hide PDF Text Block, use this under Code Block

<style>
body:not(.sqs-edit-mode) div.html-block:has(a[href*="pdf"]) {
    display: none;
}
</style>