Javascript: Inversely Proportional

I’m working on a project that uses the JScrollPane JQuery Plugin to scroll a number of records. My client wanted the scroll bar to have a variable height (like most modern scroll bars). The height of the scroll bar should be determined by the number of records – the height should decrease as the number of records increase. So the scroll bar height is inversely proportional to the number of records.

First I had to determine the number of records (stored in json record):

?View Code JAVASCRIPT
var numRecs = data.reviews.length;

I also had to determine the maximum height of the scroll bar. I wanted the scroll bar to never exceed 80% of the height of it’s container.

?View Code JAVASCRIPT
var cHeight = parseInt(('#myScroll').css('height')); 
var maxBar = Math.ceil(cHeight * .80);

I also determined if the container has 500 or more records the scroll bar height should be 20px. Now this was a bit of a random determination, but my client agreed with the logic (he wanted the scroll bar to be no smaller than 20px).

I used these values to determine the constant.

?View Code JAVASCRIPT
// xy = k 
// numRecs*barH = constant (500*20 = 10000)
// So,
// barH = constant/numRecs

So now I had my formula for inverse proportionality:

?View Code JAVASCRIPT
var maxBarHeight = '';
// if the number records is equal to or greater than 500,
// then the bar height is 20px
// else
// calculate the height of the scroll bar based upon
// the inverse proportionality formula 
if (numRecs >= 500) {
	maxBarHeight = 20;
} else {
	maxBarHeight = Math.ceil(10000/numRecs);
}
// if the bar height exceeds maximum height,
// set the bar height at 80% of it's container
if (maxBarHeight > maxBar) {
	maxBarHeight = maxBar;
}
$('#myScroll').jScrollPane({scrollbarWidth: 2, dragMaxHeight: maxBarHeight, scrollbarOnLeft: true});

Easy enough. Here’s the entire code:

?View Code JAVASCRIPT
var numRecs = data.reviews.length;
var cHeight = parseInt(('#myScroll').css('height')); 
var maxBar = Math.ceil(cHeight * .80);
if (numRecs >= 500) {
	maxBarHeight = 20;
} else {
	maxBarHeight = Math.ceil(10000/numRecs);
}
if (maxBarHeight > maxBar) {
	maxBarHeight = maxBar;
}
$('#myScroll').jScrollPane({scrollbarWidth: 2, dragMaxHeight: maxBarHeight, scrollbarOnLeft: true});

Inverse proportionality is not difficult to determine once you have the constant. Enjoy.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks