I want to implement scrolling images on my product listing page when a user hovers on the product tile. Initially the first image will be displayed and when hovered the slide show shall begin. Each product tile will have different number of images for slide show.
Issue: When hovered on an image with five images in an array, the slide show starts and second image is shown.But the instead of third image again first image is getting displayed. Below is the sequence: Number denotes the index of images 1,2 1,2,3 1,2,3,4 1,2,3,4,5 Expected: 1,2,3,4,5
Also Observed that the mouse hover event gets unregistered.
Below is the code:
<div class="customized-slider-wrapper" data-bind="PLPTileSizeOnHover: $data">
<div class="customized-slider" data-bind="foreach: fullImageURLs">
<div class="individual-tile">
<img data-bind="attr: { src: $index() === 0? $data : '../file/general/show_loader_showcase.gif' }" class="product-images" />
</div>
</div>
</div>
KO code
ko.bindingHandlers.PLPTileSizeOnHover = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var data = ko.unwrap(valueAccessor());
// Intiallizing variables for product image animation
var _index = 0;
var imgArray = data.fullImageURLs();
var toBeScrolledBy = 0;
var scroller = $(element).find('.customized-slider').eq(0);
var StopAnimation;
element.onmouseover = function () {
//Start Animation
StopAnimation = setInterval(function () {
var totalSlides = $(element).find('.customized-slider').eq(0).children();
var slideWidth = totalSlides[0] && totalSlides[0].clientWidth;
_index++;
$($(element).find('.product-images')[_index]).attr('src', imgArray[_index]);
if (_index >= imgArray.length) {
_index = 0;
}
toBeScrolledBy = slideWidth * _index;
$(scroller).css({
'transform': 'translateX(-' + toBeScrolledBy + 'px)'
});
}, 1500);
}
element.onmouseout = function () {
//End of animation and reseting the index and div postion
clearInterval(StopAnimation);
_index = 0;
$(scroller).css({
'transform': 'translateX(0)'
});
}
}
}
Requirement is to load images one by one when hovered. cannot load all images first.
Code works on chrome when dev tool is kept on.
The problem is the
mouseover
andmouseout
events. They are fired also for the element's children and bubble up. Therefore you "randomly" get these events as the children move around. Instead you want to usemouseenter
andmouseleave
.I've incorporated this change as well as some general cleanup: