I have a DOM with multiple horizontal scroll containers and prev next buttons. I’m not able to change the html so that’s what I got.
<div class="scroll_container"></div>
<div class="prev_button_wrapper">
<button class="prev_button"></div>
</div>
<div class="next_button_wrapper">
<button class="next_button"></div>
</div>
<div class="scroll_container"></div>
<div class="prev_button_wrapper">
<button class="prev_button"></div>
</div>
<div class="next_button_wrapper">
<button class="next_button"></div>
</div>
...
So far I got this.
jQuery(document).ready(function() {
jQuery(".prev_button").click(
function() {
var thumbHolder = jQuery(".scroll_container");
thumbHolder.scrollLeft(thumbHolder.scrollLeft() - 300);
}
);
jQuery(".next_button").click(
function() {
var thumbHolder = jQuery(".scroll_container");
thumbHolder.scrollLeft(thumbHolder.scrollLeft() + 300);
}
);
});
Of course the problem is, that the first prev and next buttons scroll all containers on the page. I already tried to use closest()
but I couldn’t get it work.I’m at a very basic level with Java/jQuery and appreciate any help.
2
Answers
To make your jQuery code work for each arrangement of parchment compartments and their comparing prev/next buttons, you want to utilize crossing techniques like
nearest()
andnext()
to focus on the particular holders and buttons connected with one another. Here is the changed code that ought to work accurately:With the changes above, when you click on a particular prev_button, it will view as the comparing
.scroll_container
component utilizingclosest('.prev_button_wrapper')
and afterward useprev('.scroll_container')
to get the compartment that precedes the clicked button. Additionally, for the next_button, it will view as the comparing .scroll_container component utilizingclosest('.next_button_wrapper')
and afterward useprev('.scroll_container')
to get the holder that precedes the next_button.Along these lines, the snap occasions will focus on the right parchment compartment connected with each arrangement of prev/next buttons.
Unfortunately, because the
.scroll_container
isn’t wrapped within the same parent as any individual<button>
group, usingclosest()
to find the relevant element will either fail – and simply not find the element, based on the selector passed to the method – or alternatively – depending on the selector… – find all.scroll_container
elements.This being the case, we’re required to use a somewhat complex mix of
closest()
,prevAll()
,first()
andfind()
. This would – of course – be much easier if the HTML could be adjusted, even if only in the JavaScript/jQuery to wrap elements together.Without that option, though, this is the best approach I could think of; there are explanatory comments in the code:
JS Fiddle demo.
References:
closest()
.find()
.first()
.hasClass()
.on()
.prevAll()
.scrollLeft()
.