Dynamic Child Element Heights with jQuery simplyScroll
simplyScroll is a compact little jQuery plugin that auto-scrolls child elements of a container div that you call it on with jQuery. So, for example if you have the following unordered list:
<ul id="list"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>
Then you can call simplyScroll on the list as follows:
$(document.ready(function(){
$("#list").simplyScroll({
autoMode: 'loop'
});
});
This will automatically scroll through all the elements of the list. Neat!
However, the script does a simple calculation to get the total height of the list. In the source code, the following line (line number 120) calculates the height of the list by multiplying the height of the first item by the number of items:
this.posMax = this.$items.length * this.itemMax;
So, if any of your list items are larger than the first, the height that the script sets for the container will not be big enough. I simply replaced that line with the following little loop:
max = 0;
$.each(this.$list.children(), function(index, child){
max += parseInt($(child).outerHeight(true));
});
this.posMax = max;
This sets the height of the container to the sum of all the heights of the child elements. The outerHeight method is a jQuery function that gets the height of the element, including padding and border. Including the optional "true" argument means the outerHeight() method includes the element’s margin in the height as well.
Granted, this only works if you’re using the simplyScroll to scroll vertically. You would need to use the outerWidth(true) method if you want to use the horizontal scrolling mechanism with unevenly-sized elements.
An even better solution is the following, which allows the script to continue to function for both horizontal and vertical lists, with differently sized child elements:
if (!this.o.horizontal) {
this.itemMax = this.$items[0].offsetHeight; //this.$items[0].offsetHeight;
this.clipMax = this.$clip.height(); //this.$clip[0].offsetHeight;
this.posMax = function(){
max = 0;
$.each(this.$list.children(), function(index, child){
max += parseInt($(child).outerHeight(true));
});
return max;
}
this.dimension = 'height';
this.moveBackClass = 'simply-scroll-btn-up';
this.moveForwardClass = 'simply-scroll-btn-down';
} else {
this.itemMax = this.$items[0].offsetWidth;
this.clipMax = this.$clip.width();
this.posMax = function(){
max = 0;
$.each(this.$list.children(), function(index, child){
max += parseInt($(child).outerWidth(true));
});
return max;
}
this.dimension = 'width';
this.moveBackClass = 'simply-scroll-btn-left';
this.moveForwardClass = 'simply-scroll-btn-right';
}
this.posMin = 0;
this.posMax = this.posMax();
this.$list.css(this.dimension,this.posMax +'px');
Just paste over everything from "if (!this.o.horizontal)" to "this.$list.css(this.dimension,this.posMax +’px’);" in the original script file and you should be good to go!