Swapping gallery images using jQuery and Menumill

Tom Beck's Avatar

Tom Beck

30 Sep, 2009 06:04 PM via web

One of the most common requests for gallery functionality is the ability to swap images by clicking on a thumbnail. Here is an easy example of how to do this. Check out the example site gallery: Eleni Floral, to see what I mean.

The following example is dependent on the jQuery Library. If you are familiar with jQuery, you already know how much of a pleasure it is to work with. If this is your first time... check it out: jQuery There are a ton of examples, plugins and documentation out there.


Let's begin by setting up the gallery template.

Here is an example of the html that we want to generate:

<img src="path_to_file" alt="alt_text" id="featured_image"/>
<ul id="thumbs">
  <li><a href="image_url"><img src="image_url_thumb" alt="alt_text" /></a></li>
  <li><a href="image_url"><img src="image_url_thumb" alt="alt_text" /></a></li>
   <li><a href="image_url"><img src="image_url_thumb" alt="alt_text" /></a></li>
</ul>

Here is the liquid syntax needed to generate the HTML:

<img src="{{ gallery.featured_image | asset_img_url: 'large' }}" alt="{{ gallery.featured_image.image_alt }}" id="image_featured" />
<ul id="thumbs">
  {% for image in gallery.images %}
    <li><a href="{{ image | asset_img_url: 'large' }}" title="{{ image.alt }}"><img src="{{ image | asset_img_url: 'square' }}" alt="{{ image_alt}}" /></a></li>
  {% endfor %}
</ul>

Now let's add the javascript that switches the featured image source when the user clicks a thumbnail

Make sure to include the jQuery Library from your theme's layout file (theme.liquid)

{{ 'jquery-1.3.2.min.js'   | asset_url | script_tag }}

Enter this javascript block anywhere in your gallery template

<script type="text/javascript">
$(document).ready(function(){
  $("#thumbs li a").click(function(event){
    $("#image_featured").attr("src", $(this).attr("href") );
    event.preventDefault();
  });
});
</script>

All done.

Reply to this discussion

Internal reply

Formatting help or Preview

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.