Equalising box baselines with Javascript
A while ago I wrote about creating equal height boxes using Javascript, and occasionally I find myself referring back to that article when I need the technique for a project.
Recently I added it to a layout only to find it didn’t have quite the effect I intended. One of the boxes had a top-margin applied, so equalising the box heights meant that their bottoms were still out of line – I needed a means of lining up the baseline of the boxes.
Here are the two new functions and one extra variable I added to the BoxHeights object literal from the previous article:
maxb: 0,baseline: function() {this.num = arguments.length;for (var i=0;i<this.num;i++) if (!$(arguments[i])) return;this.boxes = arguments;this.findBase();for (var i=0;i<this.num;i++) $(arguments[i]).style.height = (this.maxb - $(arguments[i]).offsetTop) + "px";},findBase: function() {var bottoms = new Array();for (var i=0;i<this.num;i++) {if (navigator.userAgent.toLowerCase().indexOf('opera') == -1) {bottoms.push($(this.boxes[i]).offsetTop + $(this.boxes[i]).scrollHeight);} else {bottoms.push($(this.boxes[i]).offsetTop + $(this.boxes[i]).offsetHeight);}}bottoms.sort(this.sortNumeric);this.maxb = bottoms[this.num - 1];}- Download this code: /code/baseline-1.txt
They are roughly equivalent to the existing equalise() and maxheight() functions, but instead of working out the height they calculate (through the power of simultaneous equations – the one thing I learned in school) which box has the lowest baseline, and then adjust the heights of each box so the baselines are the same.
Again, here’s a simple demonstration. Code is tested in IE6, FF1+, Safari 2, Opera 9.
Filed under: Javascript.
Bookmark this article with del.icio.us
Previously: Things you notice on dial-up
Next: Review: NewsGator Online