I am working on a project where I have a collection of images that need to be displayed side by side on an html page within a div. The challenge arises when the number of images exceeds the space in the div, causing it to scroll automatically from left to right and vice versa.
My goal is to create an interaction where the scrolling animation stops when the user hovers over the div, and resumes once they move their cursor away. However, I've encountered issues with this functionality as it seems to work inconsistently.
The HTML code below is generated through django:
<div class="row" style="position: relative;">
<div id='mainDiv' class="col-sm-12" style="">
<h1">Title</h1><hr>
<div style="overflow:hidden;white-space: nowrap;">
{% for img in all_images %}
<div class="" style="height:200px;display:inline-block">
<img height="100" title="" src="{{img.scr}}">
</div>
{% endfor %}
</div>
</div>
</div>
JS functionality:
function animateScroll(targetElement, speed) {
var scrollWidth = $(targetElement).get(0).scrollWidth;
var clientWidth = $(targetElement).get(0).clientWidth;
$(targetElement).animate({ scrollLeft: scrollWidth - clientWidth },
{
duration: speed,
complete: function () {
targetElement.animate({ scrollLeft: 0 },
{
duration: speed,
complete: function () {
animateScroll(targetElement, speed);
}
});
}
});
};
var animationSpeed = 20000;
animateScroll($('#mainDiv'), animationSpeed);
$("#mainDiv").hover(function(){
$(this).stop(true)
});
$("#mainDiv").mouseout(function(){
animateScroll($(this), animationSpeed);
});