Reputation: 171
I'd like to create a vertical menu with a fixed height that slides up and down when you press the arrows.
I can't wrap my head around how to work with the offsets to know where to jump to. Now I take the relative offset from the next li-item and jump to there. But it's doesn't do what it is supposed to do. And also, it's not correct. I think I'd have to know if the bottom of the UL is displayed in the div. If so, the down arrow doesn't have to move anymore. But how can I know?
//get next element
var offsetNextLi = jQuery($nextElement).position();
$liScrolledto = $nextElement;
jQuery("ul#inline_navigation").animate({
scrollTop: offsetNextLi.top
}, 500);
Here is my fiddle:
Upvotes: 1
Views: 1607
Reputation: 694
The offset is relative, but your example has a constant li height, so you could use a constant stepping. Or calculate the next invisible outer li element. To do that I worte a little jsfiddle. http://jsfiddle.net/GxL8v/3/
(function($) {
$(document).ready(function () {
//SLIDE UP
jQuery("#arrowup").on("click", function () {
var $ul = $('#inline_navigation');
var y = $ul.scrollTop();
var $firstChild = $ul.children().first();
var step = $firstChild.outerHeight() + parseInt($firstChild.css('marginBottom'),10);
console.log('before up', y, step);
if (y >= 0) {
y -= step;
console.log('after up', y);
$ul.stop().animate({
scrollTop: y
}, 100);
}
});
//SLIDE DOWN
$("#arrowdown").on("click", function () {
var $ul = $('#inline_navigation');
var y = $ul.scrollTop();
var h = $ul.height();
var $firstChild = $ul.children().first();
var step = $firstChild.outerHeight() + parseInt($firstChild.css('marginBottom'),10);
console.log('before down', y, step);
if (h >= y) {
y += step;
console.log('after down', y);
$ul.stop().animate({
scrollTop: y
}, 100);
}
});
});
}(jQuery));
This code is not optimised so, it is only for didactic reasons. The code looksup for the "ul" list every click, the y variable get's the relative coordinate by scrollTop() function of jQuery. The step could also be constant 59 for instance or as I sad before calculated.
Then checks if y breaks a border on top or down, therefore it looks for the height downwards, and checks y against 0 upwards. Rest is almost the same for up and down, only the sign changes from + to -.
Hope this helps. Code could be more reusable and optimized, todo the same with keypress.
Upvotes: 3