Resume Scroll Position Upon Scroll Stop
Fiddle I did scroll nagivation using buttons, but the problem is it seems buggy when the user scrolls using their mousewheel. So to solve this I thought of catching the scroll stop
Solution 1:
Instead of checking when the scroll has stopped, I would check the direction of the scroll instead. I have also added checking into the click functions so the scrollValue
can't go out of range leading to dead clicks of your buttons
var scrollValue = 0,
scrollAmount = 60,
ul = $('#numbers'),
maxScroll = (ul.children('li').length * scrollAmount) - ul.height(),
up = $('#up'),
down = $('#down');
down.click(function () {
if (scrollValue < maxScroll) {
scrollValue += scrollAmount;
ul.stop().animate({
scrollTop: scrollValue
});
}
});
up.click(function () {
if (scrollValue > 0) {
scrollValue -= scrollAmount;
ul.stop().animate({
scrollTop: scrollValue
});
}
});
ul.on('mousewheel DOMMouseScroll', function (e) {
e.preventDefault();
if (!$(this).is(':animated')) {
if (e.originalEvent.wheelDelta >= 0) {
up.click();
} else {
down.click();
}
}
});
ul {
padding: 0;
margin: 0;
height: 180px;
overflow: auto;
}
li {
height: 50px;
background: pink;
list-style: none;
margin-bottom: 10px;
height: 50px;
}
body {
padding: 0;
margin: 0;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulid="numbers"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li></ul><buttonid="up">up</button><buttonid="down">down</button>
Solution 2:
I think you may find a complete solution in this :
$(function() {
var itemheight = $('li').eq(0).outerHeight(true),
up, busy;
$('ul').on('wheel', function(e) {
var direction = e.originalEvent.deltaY;
if (direction < 0) up = true;
else up = false;
scrollIt();
returnfalse;
});
$('button').click(function() {
if ($(this).text() == 'up') up = true;
else up = false;
scrollIt();
});
functionscrollIt() {
if (busy) return;
busy = true;
var current = $('ul').scrollTop();
if (up) current -= itemheight;
else current += itemheight;
$('ul').animate({scrollTop: current}, 400, function() {
busy = false;
});
}
});
It prevents animation build up and will treat the mousewheel the same as if the buttons were pressed.
Solution 3:
Instead of storing scrollValue, you should calculate current scroll of the ul and add scroll ammount to that value
var scrollValue = $('ul').scrollTop();
scrollValue = scrollValue + 60;
Post a Comment for "Resume Scroll Position Upon Scroll Stop"