Javascript: Inversely Proportional
Tuesday, January 12th, 2010I’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):
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.
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.
// xy = k // numRecs*barH = constant (500*20 = 10000) // So, // barH = constant/numRecs |
So now I had my formula for inverse proportionality:
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:
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.



April 12th, 2011 at 6:34 pm
Hi, I have been reading and enjoying your posts for some time now. I appreciate your spin on things. I’m finally going to bookmark your website so I can keep returning to it. I repeatedly happen upon it and keep thinking it’s amazing but never saving it. See you next time! Keep providing us with these great writings!