Reputation: 371
I've created a DIV element with the stylesheet below
#myDiv nav {
position: relative;
display: block;
height: 315px;
overflow: hidden;
margin: 60px 0 0 0;
}
Now there is a list of UL>LI elements in it that can be of any height, I created two buttons UP and DOWN to navigate this "#myDiv nav" and the jQuery is below
jQuery(document).ready(function(){
var scrollh = 0
var scrollv = 0
jQuery(".up_nav").on("click" ,function(){
scrollv = scrollv + jQuery('#myDiv nav').innerHeight()
jQuery('#myDiv nav').stop(true, false).animate({
scrollTop: (jQuery('#myDiv nav').offset().top - scrollv)
},500);
});
jQuery(".down_nav").on("click" ,function(){
scrollh = scrollh + jQuery('#myDiv nav').innerHeight()
jQuery('#myDiv nav').stop(true, false).animate({
scrollTop: scrollh
},500);
});
});
PROBLEM
The first few clicks on UP and DOWN works well with me but after these few clicks, The scrolling goes extreme UP or extreme DOWN.
I wanted this to be a normal behaviour, Scrolling up and down according to the height of UL element that resides in "#myDiv nav" and in small steps.
EDIT
I've uploaded the working version of my problem to the jsfiddle website Link to JSFIDDLE, You will notice the problem after clicking the up or down button few times.
I understand my jQuery logic has a flaw in it but i am unable to understand it.
Upvotes: 1
Views: 1491
Reputation: 106
You can make
ul {
position: absolute;
top: 0px;
transition: top 0.5s;
}
and next just change top style on ul after clicking on the button.
Check example:
http://jsfiddle.net/DariuszMusielak/oxgbyk6b/1/ <---- UPDATED
UPDATE v2 http://jsfiddle.net/DariuszMusielak/jrtfrgo2/
Upvotes: 0
Reputation: 6199
This will be a little closer to what you're looking for. It's implemented with the concept of pages.
http://jsfiddle.net/ue94jj60/6/
var Grid = function () {
var self = this;
var page = 1,
nav = null;
this.init = function () {
nav = $('#myDiv nav');
$(".up_nav").on("click", function () {
self.scroll(page - 1);
});
$(".down_nav").on("click", function () {
self.scroll(page + 1);
});
};
this.pages = function () {
return Math.round(nav[0].scrollHeight / nav.innerHeight());
};
this.scroll = function (p) {
if (p < 1 || p > this.pages()) {
return;
}
page = p;
nav.stop(true, false).animate({
scrollTop: (page - 1) * nav.innerHeight()
}, 500);
};
$(this.init);
};
var grid = new Grid();
You can also scroll it programmatically:
grid.scroll(3);
Upvotes: 2