fbpx

jQuery – Find a set’s bounding rectangle

Overlapping colored triangles

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.

About the Author:

Visionfriendly.com

Visionfriendly.com

VisionFriendly.com has been building successful websites for over 20 years and covers all areas of website design, development and marketing with creative custom web designs and a robust in-house team of programmers to get your web marketing to work exactly the way you need it to.

Share On:

Share on facebook
Share on twitter
Share on linkedin

Comments:

Leave a Comment

Your email address will not be published. Required fields are marked *

Copyright © 2021, All Rights Reserved
Tri Colored Triangles
Scroll to Top

Take your business to the

Next Level!

Visionfriendly.com has the right team to make your business stand out from other professional websites.

Ready For Takeoff?

A Completely Customized
Digital Marketing Experience

We'll be in touch within one business day to discuss your goals and create a personalized plan that fits both you and your business.

Let’s start a Conversation