Jump to content

Switch Between Images By Clicking Text?

Go to solution Solved by jpeter,

Recommended Posts

Site URL: https://www.srcartunes.com/

Hi all! 

I had my client ask me if we could do something similar to this on his site: https://www.3m.com/3M/en_US/automotive-window-solutions-us/automotive-window-film-simulator/  I've never tried switching between images triggered by text before so I have no clue how to even go about it.

Wondering if this is even possible on Squarespace?

The client site is https://www.srcartunes.com/

Thanks in advance for any help!

Link to comment
  • Solution

@nicolemeza You could use the following JS below. You'll need to make sure you enable thumbnails on your slideshow gallery because the JS code relies on them being there. The text that is used is based on the alt text of the thumbail images.

You can update the config.position to be "top" or "bottom" to position the links above or below the slideshow and the config.hideThumbails to true or false to hide or show the thumbnails:

javascript

(function () {

    /**********************************************************************************
     * REQUIREMENTS
     * - This code will only be ran if there's a Slideshow Gallery Block on the page
     * - This code SHOULD have thumbnails enabled. You can hide them using the
     *   config defined below
     **********************************************************************************/

    /**********************************************************************************
     * CONFIGURATION
     **********************************************************************************/
    var config = {}; // DO NOT DELETE
    
    // Choose "top" or "bottom"
    config.position = 'top';
  
    // Choose true or false
    config.hideThumbnails = false;
  
    // Customize the class name of the container that wraps the links
    config.containerClass = 'sqs-gallery-thumbnail-links';
  
    // Customize the class name of the links themselves
    config.linkClass = 'sqs-gallery-thumbnail-link';
  
    // Customize the active class name that gets added to the link
    config.activeClass = 'sqs-active-slide';


    /**********************************************************************************
     * DO NOT MODIFY the code below unless you know what you're doing.
     **********************************************************************************/
  
     // Initialize code depending on if the DOM has been fully loaded or not.
    if(document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', init);
    } else {
      init();
    }
  
  
    function init(){
      addPolyfills();
  
      var galleryBlocks = document.querySelectorAll('.gallery-block');
      var thumbnailLinksPosition, thumbnails, div, html, altText, id;
  
      // Exit if there are no gallery blocks on the page.
      if(!galleryBlocks) return;
      
      galleryBlocks.forEach(function(gallery){
        var slideshow = gallery.querySelector('.sqs-gallery-block-slideshow.sqs-gallery-has-thumbnails');
  
        // Exit if the gallery is not a slidshow and does not have thumbnails
        if(!slideshow) return;
  
        thumbnailContainer = gallery.querySelector('.sqs-gallery-thumbnails');
        thumbnails         = gallery.querySelectorAll('.sqs-gallery-thumbnails img');

        // Create div container that links will go in.
        div                = document.createElement('div');
        div.setAttribute('class', config.containerClass);
        addClass(div, config.containerClass);
        addClass(div, 'position--' + config.position);
        html = '';
        
        // Loop over each thumbnail and create a link based on it's alt text
        thumbnails.forEach(function(thumbnail, index){
          altText = thumbnail.getAttribute('alt');
          id = thumbnail.getAttribute('id');
          var classes = [
            config.linkClass,
            index == 0 ? config.activeClass : ''
          ].join(' ');

          if(altText){
            html += '<a class="' + classes +'" href="#' + id + '">' + altText + '</a>';
          }
        });

        // Add html to div container
        div.innerHTML = html;

        // Figure out the position to use for the Element.insertAdjacentElement 
        // method based based on config.
        switch(config.position) {
          case 'top':
            thumbnailLinksPosition = 'afterbegin';
            break;
          case 'bottom':
            thumbnailLinksPosition = 'beforeend';
            break
        }

        // Add thumbnails to top or bottom based on config.
        gallery.insertAdjacentElement(thumbnailLinksPosition, div);

        // Hide thumbnails based on config.
        if(config.hideThumbnails) {
          thumbnailContainer.style.display = 'none';
        }


         // Options for the observer (which mutations to observe)
         var options = { attributes: true, subtree: true };

         // Create an observer instance linked to the callback function
         var observer = new MutationObserver(function () {
           var activeSlide = thumbnailContainer.querySelector('.sqs-active-slide');
           var id = activeSlide.getAttribute('id');
           var links = gallery.querySelectorAll('.' + config.containerClass + ' .' + config.linkClass);
           links.forEach(function(link){
            removeClass(link, config.activeClass);
           });
           var link = gallery.querySelector('.'+config.linkClass + '[href="#'+ id +'"]');
           addClass(link, config.activeClass);
         });
         // Start observing the target node for configured mutations
         observer.observe(thumbnailContainer, options);
  
      });
  
      // Use Event delegation for all of the links that are going to be clicked
      delegate(document, 'click', '.sqs-gallery-thumbnail-link', function (event) {
        event.preventDefault();
        var link = event.target;
        var id = link.getAttribute('href');
  
        link.parentElement.querySelectorAll('.sqs-gallery-thumbnail-link').forEach(function(el){
          removeClass(el, config.activeClass);
        });
  
        addClass(link, config.activeClass);
  
        document.querySelector(id).click();
      });
    }
  
    function delegate(target, eventName, selector, handler) {
      target.addEventListener(eventName, function (event) {
        if (matches(event)) {
          handler(event);
        }
      });
  
      function matches(event) {
        const element = event.target.closest(selector);
        return element !== null;
      };
    }
  
    function hasClass(el, className) {
      return el.classList ? el.classList.contains(className) : new RegExp('\\b'+ className+'\\b').test(el.className);
  }
  
    function addClass(el, className) {
        if (el.classList) el.classList.add(className);
        else if (!hasClass(el, className)) el.className += ' ' + className;
    }
  
    function removeClass(el, className) {
        if (el.classList) el.classList.remove(className);
        else el.className = el.className.replace(new RegExp('\\b'+ className+'\\b', 'g'), '');
    }
  
    function addPolyfills() {
      nodeListForEachPolyfill();
      closestPolyfill();
    }
  
    function nodeListForEachPolyfill() {
      if (window.NodeList && !NodeList.prototype.forEach) {
        NodeList.prototype.forEach = Array.prototype.forEach;
      }
    }
  
    function closestPolyfill() {
      if (!Element.prototype.matches) {
        Element.prototype.matches = Element.prototype.msMatchesSelector ||
          Element.prototype.webkitMatchesSelector;
      }
  
      if (!Element.prototype.closest) {
        Element.prototype.closest = function (s) {
          var el = this;
  
          do {
            if (Element.prototype.matches.call(el, s)) return el;
            el = el.parentElement || el.parentNode;
          } while (el !== null && el.nodeType === 1);
          return null;
        };
      }
    }
  
  })();

Be sure to include the JS code above in between <script> tags:
 

<script>
  // Add JS Code Here
</script>

Then add CSS:

.sqs-gallery-thumbnail-links {
  text-align: center;
}

.sqs-gallery-thumbnail-links.position--top {
  margin-bottom: 2rem;
}

.sqs-gallery-thumbnail-link {
  font-size: 1.3rem;
  margin-left: 1rem;
  margin-right: 1rem;
  margin-top: 1rem;
  display: inline-block;
}

.sqs-gallery-thumbnail-link.sqs-active-slide {
  color: red;
}

Working example:

 

Edited by jpeter
Link to comment

This is awesome! Thanks! So, I'm not very savvy with Javascript, but I tried inserting this based on your instructions and its saying "Script Disabled" on the code block. I have a slideshow gallery block with thumbnails enabled. 

 

It's also cutting off everything on the page below the code block. 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.