I'm using jQuery to swap images on hover. There's a main image, and a gallery of thumbs. When the thumb is hovered over/touched, the larger version of it populates the main image, and the smaller version of the original populates the thumb. This happens via swapping src
and data-
attributes.
This all works, but being relatively new to JS/jQuery, the code is probably a little clunky and could use a keener eye. I don't fully grasp callbacks (among other JS things) yet, so I imagine there'll be some streamlining/chuckling with that.
function large_to_thumb(imageHovered, mainLarge, mainThumb){
$(imageHovered).attr('src', mainThumb).data('large', mainLarge);
}
function thumb_to_large(image, mainLarge, mainThumb){
var mainImage = $('.main-image');
// 1. put gallery image data-large into .main-large src
mainImage.attr('src', $(image).data('large'));
// 2. put gallery image src into .main-large data-gallery-image
mainImage.data('gallery-image', $(image).attr('src'));
large_to_thumb(image, mainLarge, mainThumb);
}
$('.product-gallery img').on('mouseenter touch', function(){
var mainLarge = $('.product-image .main-image').attr('src');
var mainThumb = $('.product-image .main-image').data('gallery-image');
thumb_to_large(this, mainLarge, mainThumb);
});
li {
display:inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product-image">
<img class="main-image" src="http://placehold.it/300x300" data-gallery-image="http://placehold.it/150x150">
<div class="product-gallery">
<ul>
<li>
<img src="http://placehold.it/149x149" data-large="http://placehold.it/299x299">
</li>
<li>
<img src="http://placehold.it/148x148" data-large="http://placehold.it/298x298">
</li>
</ul>
</div>
</div>