I just came across this great jQuery extension that finds the bounding box of a wrapped set of jQuery objects. (You do know what a wrapped set is, right?)
The code is based off a post on Andrew McHarg's Read Eval Bacon Loop. His original function returns a Javascript object {left, top, right, bottom}
. I've modified it to also return width and height, so that you can pass it directly to jQuery's css()
function to directly set the bounds of some other element.
Here's the extension:
(function() {jQuery.fn['bounds'] = function () {
var bounds = {
left: Number.POSITIVE_INFINITY,
top: Number.POSITIVE_INFINITY,
right: Number.NEGATIVE_INFINITY,
bottom: Number.NEGATIVE_INFINITY,
width: Number.NaN,
height: Number.NaN
};
this.each(function (i,el) {
var elQ = $(el);
var off = elQ.offset();
off.right = off.left + $(elQ).width();
off.bottom = off.top + $(elQ).height();
if (off.left < bounds.left)
bounds.left = off.left;
if (off.top < bounds.top)
bounds.top = off.top;
if (off.right > bounds.right)
bounds.right = off.right;
if (off.bottom > bounds.bottom)
bounds.bottom = off.bottom;
});
bounds.width = bounds.right - bounds.left;
bounds.height = bounds.bottom - bounds.top;
return bounds;
}})();
And here's an example:
var bounds = $(".some-objects").bounds();
$("#other-object").css(bounds);
I'm using this along with jQuery UI's resizable()
extension to overlay a <div>
atop some other DOM elements.