Reputation: 701
I need to do something like simple vertical carousel. On hover
and scroll
I need to scroll inner ul
to the next or previous li
element (it depends on scroll direction), change class current
for current element and classes prev
and past
for previous and next elements accordingly.
HTML
<div id="scroll">
<ul>
<li style="background: red;"></li>
<li style="background: green;"></li>
<li style="background: yellow;"></li>
<li style="background: blue;"></li>
</ul>
</div>
jQuery
$.fn.scroll = function () {
var $this = $(this);
var $list = $(this).find('ul');
var $lis = $list.find('li');
var count = $lis.length;
var direction,
currentSlidePosition;
$this.addClass('scroll');
$list.addClass('slides-list');
$lis.addClass('slide');
$lis.filter(':first').addClass('current');
$lis.filter(':not(:first)').addClass('past');
var scrollHeight = $lis.eq(0).height();
function gotoSlide(direction) {
currentSlidePosition = $lis.filter('.current').index();
if ((direction === 1 && currentSlidePosition === 0) || (direction === -1 && currentSlidePosition === count - 1)) {
return;
}
$lis.removeClass('current');
$lis.eq(currentSlidePosition - direction).removeClass('past prev').addClass('current');
$lis.filter('.current').prevAll().addClass('prev');
$lis.filter('.current').nextAll().addClass('past');
$list.animate({
scrollTop: (direction === -1) ? scrollHeight : -scrollHeight
}, {
duration: 300
});
}
$this.on('mouseenter', function () {
var $this = $(this);
$this.bind('mousewheel', function (e) {
if ($list.is(':animated')) {
return;
}
if (e.originalEvent.wheelDelta > 0) {
direction = 1; //up
} else {
direction = -1; //down
}
gotoSlide(direction);
});
});
};
$(document).ready(function () {
$('#scroll').scroll();
});
The problem is scrolling works properly only for the first element and doesn't work for other ones, although changing of the classes works the right way. What's the problem, how to fix it?
Upvotes: 1
Views: 59
Reputation: 17144
You need to increment scroll depending on where current scroll is at. Right now you're reassigning without taking into consideration where you're at. Like this:
$list.animate({
scrollTop: (direction === -1) ? $list.scrollTop()+scrollHeight : $list.scrollTop()-scrollHeight
}
http://jsfiddle.net/m5unj2wu/1/
Upvotes: 1