Our Black Friday Sale has been extended!  View Sale

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 = {
		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();

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 is a Chicago digital marketing agency with over 25 years of experience helping clients nationwide. We have an in-house team of marketers and creatives ready to improve your business’s marketing operations.

Share On:


Leave a Comment

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

Copyright © 2023, 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.

  • This field is for validation purposes and should be left unchanged.

Let’s start a Conversation