I am trying to develop an interface that scrolls horizontally similar to Netflix
.
First, I would give the parent div a class like scroll-container
.
Then, I would pass the parent div as an argument to startScrolling
.
parent = $(this).closest('.scroll-container')
startScrolling(direction, scrollStep, parent)
Then, you have access to the parent and don't have to set it at the top of the js.
As an aside, if you're setting scrollStep
at the top as a sort of configurable constant, you don't need to pass it in as an argument. startScrolling
looks like it should work just fine without it.
As another aside, I could see startScrolling
just taking one argument: the parent div. And the data-modifier
could just live there instead of having to live in 2 places. And you could just get the modifier from the parent in the startScrolling
function.
Update
$(function () {
var scrollHandle = 0,
scrollStep = 5;
//Start the scrolling process
$(".sliderButton").on("mouseenter", function () {
var data = $(this).data('scrollModifier'),
direction = parseInt(data, 10);
$(this).addClass('active');
parent = $(this).closest('.scroll-container');
startScrolling(direction, scrollStep, parent);
});
//Kill the scrolling
$(".sliderButton").on("mouseleave", function () {
stopScrolling();
$(this).removeClass('active');
});
//Actual handling of the scrolling
function startScrolling(modifier, step, parent) {
if (scrollHandle === 0) {
scrollHandle = setInterval(function () {
var newOffset = parent.scrollLeft() + (scrollStep * modifier);
parent.scrollLeft(newOffset);
}, 10);
}
}
function stopScrolling() {
clearInterval(scrollHandle);
scrollHandle = 0;
}
});