Question

I have a script which changes the images of several list elements when clicking on thumbnails below the images, think of a color swatch. The script is swapping the src and a custom data-hover-src attribute (main image and hover image), the jquery function's variables inside the HTML onclick attribute are populated with PHP.

The swap of the main images is working fine, but the hover image (data-hover-src attribute) of the main image does not get updated after clicking a thumbnail.

Here's a fiddle which illustrates the problem: http://jsfiddle.net/YN3LV/14/

Image swap when hovering over main image:

 window.HoverImage = function () {
     var $this = $(this);
     var HoverUrl = $this.data('hover-src');
     $this.data('hover-src', $this.attr('src'));
     $this.attr('src', HoverUrl);
 };

 $(function () {
     $('img.image_update').hover(HoverImage, HoverImage);
 });

Update main image when clicking thumbnail

 function UpdateImage(color, defaultimage, hoverimage) {
     var SelectedColor = color;
     var DefaultUrl = defaultimage;
     var HoverUrl = hoverimage;
     $(".swatch_" + SelectedColor).click(function () {
         $(".swatch_" + SelectedColor).closest("ul").prev().attr({
             src: DefaultUrl,
                 "data-hover-src": HoverUrl
         });
     });
 }

I have tried setting the HoverUrl variable as global by omitting the var, "resetting" it with undefined at the end of the update image function but nothing worked. How can I resolve this and is there a smarter way of doing this, e.g. by combining everything in one function?

Était-ce utile?

La solution

Wow this is pretty cool, took me a bit but this seems to work consistently. Fiddle

Basically, the data selector did not seem to work for our situation. So I used attr instead. Perhaps mixing them is the real problem.

 HoverUrl = $this.attr('data-hover-src');
 DefaultUrl = $this.attr('src');
 $this.attr('data-hover-src',DefaultUrl );
 $this.attr('src', HoverUrl);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top