Search code examples
javascriptthumbnailsswap

Pulling alt/title tags from a thumbnail image when swapping out featured image?


I am using a pretty basic Javascript function to swap out featured images depending on which thumbnail the user clicks. The image swaps out fine, but the title/alt tags always remain the same as the default featured image which is shown on page load. I am wondering how I can pull the alt/title tags over from the thumbnail images when they are selected. Any help greatly appreciated!

UPDATE edited to reflect working code thanks to ROK!

HTML:

<div id="product-photos">

{% if product.images.size == 0 %}

  <div id="product-photo-container">
    <img src="{{ '' | product_img_url: 'grande' }}" title="{{ image.alt | escape }}" title="{{ image.alt | escape }}" alt="{{ image.alt | escape }}" />
  </div>

{% else %}

  <div id="product-photo-container">
    <img src="{{ product.featured_image.src | product_img_url: 'grande' }}" title="{{ product.featured_image.alt | escape }}" alt="{{ product.featured_image.alt | escape }}" />
  </div>

  {% if product.images.size > 1 %}
  <ul id="product-photo-thumbs" class="clearfix grid">
    {% for image in product.images %}
    <li class="product-photo-thumb">
      <a href="{{ image.src | product_img_url: 'grande' }}" data-title="{{ image.alt }}" data-alt="{{ image.alt }}">
        <img src="{{ image.src | product_img_url: 'small' }}" title="{{ image.alt | escape }}" alt="{{ image.alt | escape }}" />
      </a>
    </li>
    {% endfor %}
  </ul>
  {% endif %}      

{% endif %}

</div><!-- #product-photos -->

Javscript:

// Load variant image into feature area
$('.product-photo-thumb a').click(function(e) { e.preventDefault();
    $elem = $(this);
    var newAttributes = {
        src: $elem.attr('href'),
        title: $elem.data('title'),
        alt: $elem.data('alt')
    }
    $('#product-photo-container img').attr(newAttributes);
});

Solution

  • Javascript for this would look something like this:

    // Load variant image into feature area
    $('.product-photo-thumb a').click(function(e) { e.preventDefault();
        $elem = $(this).find('img')[0];
        var newAttributes = {
            src: $elem.attr('src'),
            title: $elem.attr('title'),
            alt: $elem.attr('alt')
        }
        $('#product-photo-container img').attr(newAttributes);
    });
    

    Read all of the parameters directly from the image and reapply them to the feature img.