I have a list of images showing and each image got a list of 1 or more additional thumbnail images.
When use hovers on one of the additonal images, the main image has to change with that addional image's source, and when mouse leaves that thumbnail, the original main image source comes back.
I managed to make it work but it only updates the source with the last thumnbail in found in the loop, so I'm basically stuck here is my code which is not working at the moment
<div>
<img class="mainImg" src="http://mysource.com/img.jpg"/>
</div>
<div class="additionalImg">
<?php
$product = Mage::getModel('catalog/product')->load($_product->getId());
/* getting additional images url */
foreach ($product->getMediaGalleryImages() as $image) {?>
<!-- thumbnails -->
<a href="<?php echo $image->getUrl();?>">
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail', $image->getFile())->resize(60, 60); ?>"
width="60" height="60" alt="" title="" />
</a>
<!-- end thumbnails -->
<script>
// var newSrc = jQuery('.additionalImg a img').attr('src');
jQuery('.additionalImg a').hover(function(){
jQuery('.mainImg').attr("src", newSrc)
});
</script>
<?php };?>
</div>
Thanks a lot
Try this:
UPDATE: The markup shown in your codepaste is invalid because you have duplicate id attributes in your container divs. You didn't make it clear in your original question that all of the code shown was repeated several times. Change each
id="product"
toclass="product"
and the following code will work:Demo: http://jsfiddle.net/s9Rhx/2/
Include the above JavaScript once on your page, not once per product div.
The above works by firstly looping through all of the
mainImg
divs and storing their original default image src. Then it binds the event handler directly to the img elements in the thumbnail anchors. On hover it uses.closest()
to navigate up to the containingclass="product"
div (don't forget to change theid
to aclass
), then.find()
to get back down to themainImg
div within the current container.First you have multiple IDs on same page which is wrong. I changed each id to class so it become
class="product"
Complete demo: http://jsbin.com/AWoNimO/2/edit
Demo HTML as you provided - I have added few dummy images for the demo:
Javascript: