Home
Dynamic Testimonial Switcher
💬

Dynamic Testimonial Switcher

Industry-Specific Social Proof

Smart testimonial management system that automatically displays industry-relevant testimonials based on UTM parameters, referrer data, and visitor characteristics for enhanced social proof and conversion optimization.

PersonalizationIntermediatePersonalization & Social Proof

Key Features

Industry-specific testimonials
UTM-based testimonial selection
Referrer-based social proof
Custom testimonial database
Fallback testimonial handling
A/B testing integration

Script Overview

📖

What It Does

This script dynamically displays testimonials most relevant to the visitor's industry or persona, increasing social proof effectiveness and conversion rates through targeted messaging.

🎯

Use Case

Perfect for B2B companies serving multiple industries. Shows healthcare testimonials to healthcare visitors, tech testimonials to tech visitors, etc.

Key Benefits

  • Industry-specific social proof
  • Higher conversion rates
  • Improved relevance
  • Better user engagement
  • Automated personalization
  • Enhanced credibility

JavaScript Code

<script>
// Dynamic Testimonial Switcher Script  
// Version: 1.0
// Last Updated: 2025-09-09

(function() {
  'use strict';
  
  var config = {
    // Testimonial database organized by industry/persona
    testimonials: {
      healthcare: [
        {
          name: 'Dr. Sarah Johnson',
          title: 'Chief Medical Officer',
          company: 'Regional Health Systems',
          text: 'This solution improved our patient care efficiency by 40%.',
          image: '/testimonials/healthcare-1.jpg'
        },
        {
          name: 'Michael Chen, RN',
          title: 'Head of Nursing',
          company: 'Metropolitan Hospital',
          text: 'Streamlined our workflows and reduced administrative burden significantly.',
          image: '/testimonials/healthcare-2.jpg'
        }
      ],
      
      technology: [
        {
          name: 'Alex Rodriguez',
          title: 'CTO',
          company: 'TechStart Inc.',
          text: 'Scaled our development process 3x faster than expected.',
          image: '/testimonials/tech-1.jpg'
        },
        {
          name: 'Jennifer Kim',
          title: 'Engineering Manager',
          company: 'DevCorp Solutions',
          text: 'Best investment we made for our engineering team this year.',
          image: '/testimonials/tech-2.jpg'
        }
      ],
      
      finance: [
        {
          name: 'Robert Williams',
          title: 'CFO',
          company: 'Capital Investments',
          text: 'Reduced our financial reporting time by 60% while improving accuracy.',
          image: '/testimonials/finance-1.jpg'
        },
        {
          name: 'Lisa Thompson',
          title: 'Financial Controller',
          company: 'Global Finance Group',
          text: 'Compliance has never been easier with this comprehensive solution.',
          image: '/testimonials/finance-2.jpg'
        }
      ],
      
      ecommerce: [
        {
          name: 'David Martinez',
          title: 'E-commerce Director',
          company: 'Online Retail Co.',
          text: 'Increased our conversion rate by 25% in the first month.',
          image: '/testimonials/ecommerce-1.jpg'
        },
        {
          name: 'Amanda Foster',
          title: 'Digital Marketing Manager',
          company: 'ShopSmart',
          text: 'ROI improved dramatically with better customer insights.',
          image: '/testimonials/ecommerce-2.jpg'
        }
      ]
    },
    
    // Industry detection mappings
    industryMappings: {
      // UTM source mappings
      utm_source: {
        'healthcare-digest': 'healthcare',
        'medical-times': 'healthcare',
        'techcrunch': 'technology',
        'hacker-news': 'technology',
        'finance-weekly': 'finance',
        'wall-street': 'finance',
        'ecommerce-news': 'ecommerce',
        'retail-weekly': 'ecommerce'
      },
      
      // UTM campaign mappings
      utm_campaign: {
        'healthcare-solutions': 'healthcare',
        'medical-efficiency': 'healthcare',
        'tech-scaling': 'technology',
        'developer-tools': 'technology',
        'financial-reporting': 'finance',
        'compliance-suite': 'finance',
        'ecommerce-growth': 'ecommerce',
        'online-retail': 'ecommerce'
      },
      
      // UTM content mappings
      utm_content: {
        'healthcare': 'healthcare',
        'medical': 'healthcare',
        'tech': 'technology',
        'developer': 'technology',
        'finance': 'finance',
        'accounting': 'finance',
        'ecommerce': 'ecommerce',
        'retail': 'ecommerce'
      }
    },
    
    // Element selectors for testimonials
    selectors: {
      container: '[data-testimonial-container], .testimonial-section',
      name: '[data-testimonial-name], .testimonial-name',
      title: '[data-testimonial-title], .testimonial-title', 
      company: '[data-testimonial-company], .testimonial-company',
      text: '[data-testimonial-text], .testimonial-text',
      image: '[data-testimonial-image], .testimonial-image'
    },
    
    // Animation settings
    animation: {
      enabled: true,
      duration: 500,
      easing: 'ease-in-out'
    },
    
    // Rotation settings
    rotation: {
      enabled: true,
      interval: 8000, // 8 seconds
      pauseOnHover: true
    },
    
    // Fallback industry if no match
    defaultIndustry: 'technology',
    
    debug: false
  };

  var currentIndustry = null;
  var rotationTimer = null;
  var testimonialIndex = 0;

  function debugLog(message, data) {
    if (config.debug) {
      console.log('[Testimonial Switcher] ' + message, data || '');
    }
  }

  function getUTMParameters() {
    var urlParams = new URLSearchParams(window.location.search);
    var params = {};
    
    ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'].forEach(function(param) {
      var value = urlParams.get(param);
      if (value) {
        params[param] = value.toLowerCase();
      }
    });
    
    // Try stored UTM data if no current params
    if (Object.keys(params).length === 0) {
      try {
        var stored = localStorage.getItem('utm_data');
        if (stored) {
          var data = JSON.parse(stored);
          Object.keys(data).forEach(function(key) {
            if (key.startsWith('utm_') && data[key]) {
              params[key] = data[key].toLowerCase();
            }
          });
        }
      } catch (e) {
        debugLog('Error reading stored UTM data:', e);
      }
    }
    
    return params;
  }

  function detectIndustry(utmParams) {
    var detectedIndustry = null;
    
    // Check each UTM parameter against industry mappings
    Object.keys(utmParams).forEach(function(param) {
      var value = utmParams[param];
      
      if (config.industryMappings[param] && config.industryMappings[param][value]) {
        detectedIndustry = config.industryMappings[param][value];
        debugLog('Industry detected from ' + param + ':', { value: value, industry: detectedIndustry });
      }
    });
    
    return detectedIndustry || config.defaultIndustry;
  }

  function getTestimonialsForIndustry(industry) {
    return config.testimonials[industry] || config.testimonials[config.defaultIndustry] || [];
  }

  function animateTestimonialChange(elements, testimonial, callback) {
    if (!config.animation.enabled) {
      callback();
      return;
    }
    
    var container = elements.container;
    if (!container) {
      callback();
      return;
    }
    
    // Fade out
    container.style.transition = 'opacity ' + config.animation.duration + 'ms ' + config.animation.easing;
    container.style.opacity = '0';
    
    setTimeout(function() {
      callback();
      
      // Fade in
      container.style.opacity = '1';
      
      // Clean up
      setTimeout(function() {
        container.style.transition = '';
      }, config.animation.duration);
      
    }, config.animation.duration);
  }

  function updateTestimonialContent(testimonial) {
    var elements = {
      container: document.querySelector(config.selectors.container),
      name: document.querySelector(config.selectors.name),
      title: document.querySelector(config.selectors.title),
      company: document.querySelector(config.selectors.company),
      text: document.querySelector(config.selectors.text),
      image: document.querySelector(config.selectors.image)
    };
    
    if (!elements.container) {
      debugLog('Testimonial container not found');
      return;
    }
    
    function applyTestimonial() {
      if (elements.name && testimonial.name) {
        elements.name.textContent = testimonial.name;
      }
      
      if (elements.title && testimonial.title) {
        elements.title.textContent = testimonial.title;
      }
      
      if (elements.company && testimonial.company) {
        elements.company.textContent = testimonial.company;
      }
      
      if (elements.text && testimonial.text) {
        elements.text.textContent = testimonial.text;
      }
      
      if (elements.image && testimonial.image) {
        if (elements.image.tagName === 'IMG') {
          elements.image.src = testimonial.image;
          elements.image.alt = testimonial.name + ' from ' + testimonial.company;
        }
      }
      
      // Mark container with industry
      elements.container.setAttribute('data-testimonial-industry', currentIndustry);
      elements.container.setAttribute('data-testimonial-index', testimonialIndex);
      
      debugLog('Testimonial updated:', testimonial);
    }
    
    if (config.animation.enabled && elements.container.style.opacity !== '0') {
      animateTestimonialChange(elements, testimonial, applyTestimonial);
    } else {
      applyTestimonial();
    }
  }

  function rotateTestimonials() {
    var testimonials = getTestimonialsForIndustry(currentIndustry);
    
    if (testimonials.length === 0) {
      debugLog('No testimonials found for industry:', currentIndustry);
      return;
    }
    
    if (testimonials.length === 1) {
      // Only one testimonial, no need to rotate
      updateTestimonialContent(testimonials[0]);
      return;
    }
    
    // Show current testimonial
    updateTestimonialContent(testimonials[testimonialIndex]);
    
    // Move to next testimonial
    testimonialIndex = (testimonialIndex + 1) % testimonials.length;
    
    // Schedule next rotation
    if (config.rotation.enabled) {
      rotationTimer = setTimeout(rotateTestimonials, config.rotation.interval);
    }
  }

  function startRotation() {
    if (rotationTimer) {
      clearTimeout(rotationTimer);
    }
    
    if (config.rotation.enabled) {
      rotateTestimonials();
    } else {
      // Just show first testimonial
      var testimonials = getTestimonialsForIndustry(currentIndustry);
      if (testimonials.length > 0) {
        updateTestimonialContent(testimonials[0]);
      }
    }
  }

  function stopRotation() {
    if (rotationTimer) {
      clearTimeout(rotationTimer);
      rotationTimer = null;
    }
  }

  function setupHoverPause() {
    if (!config.rotation.pauseOnHover) return;
    
    var container = document.querySelector(config.selectors.container);
    if (!container) return;
    
    container.addEventListener('mouseenter', function() {
      stopRotation();
      debugLog('Rotation paused on hover');
    });
    
    container.addEventListener('mouseleave', function() {
      startRotation();
      debugLog('Rotation resumed after hover');
    });
  }

  function trackTestimonialSwitch(industry, testimonial) {
    window.dataLayer = window.dataLayer || [];
    
    window.dataLayer.push({
      event: 'testimonial_switched',
      testimonial_industry: industry,
      testimonial_name: testimonial.name,
      testimonial_company: testimonial.company,
      page_url: window.location.href
    });
    
    debugLog('Testimonial switch tracked:', { industry: industry, testimonial: testimonial });
  }

  function initTestimonialSwitcher() {
    debugLog('Initializing Dynamic Testimonial Switcher');
    
    var utmParams = getUTMParameters();
    currentIndustry = detectIndustry(utmParams);
    
    debugLog('Detected industry:', currentIndustry);
    debugLog('UTM parameters:', utmParams);
    
    var testimonials = getTestimonialsForIndustry(currentIndustry);
    if (testimonials.length === 0) {
      debugLog('No testimonials available for industry:', currentIndustry);
      return;
    }
    
    // Track initial testimonial
    trackTestimonialSwitch(currentIndustry, testimonials[0]);
    
    // Setup hover pause
    setupHoverPause();
    
    // Start testimonial display/rotation
    startRotation();
  }

  // Initialize when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initTestimonialSwitcher);
  } else {
    initTestimonialSwitcher();
  }

  // Handle page visibility changes
  document.addEventListener('visibilitychange', function() {
    if (document.visibilityState === 'hidden') {
      stopRotation();
    } else if (document.visibilityState === 'visible') {
      startRotation();
    }
  });

  // Expose utility functions
  window.testimonialSwitcher = {
    getCurrentIndustry: function() {
      return currentIndustry;
    },
    getAvailableIndustries: function() {
      return Object.keys(config.testimonials);
    },
    switchToIndustry: function(industry) {
      if (config.testimonials[industry]) {
        currentIndustry = industry;
        testimonialIndex = 0;
        startRotation();
        debugLog('Manually switched to industry:', industry);
      }
    },
    addTestimonial: function(industry, testimonial) {
      if (!config.testimonials[industry]) {
        config.testimonials[industry] = [];
      }
      config.testimonials[industry].push(testimonial);
      debugLog('Testimonial added:', { industry: industry, testimonial: testimonial });
    }
  };

})();
</script>

💡 Pro Tip: Copy the entire code block above and paste it directly into a GTM Custom HTML tag. The script is self-contained and ready to use immediately.