Find the nearest BoundingClientRect

I have an array of ClientRect objects which I got by doing

var trackedElements = $('[track]');
var trackedBounds = [];
_.each(trackedBounds, function(elem) {
    return $(elem)[0].getBoundingClientRect();
});

      

I also have another element limiting the client's address.

var currentElement = $('.active')[0].getBoundingClientRect();

My question is, how do I find in trackedBounds

, which is closest to the north of currentElement

?

+3


source to share


1 answer


I think you can filter for rectangles that are not north of currentElement

:

trackedBounds = trackedBounds.filter(rect => rect.bottom > currentElement.top)

      

and sort the remaining rectangles in the property .bottom

:



trackedBounds = trackedBounds.sort((rect1, rect2) => rect1.bottom - rect2.bottom)

      

The result is the first element of the array trackedBounds

:

let result = trackedBounds
    .filter(rect => rect.bottom > currentElement.top)
    .sort((rect1, rect2) => rect1.bottom - rect2.bottom)
    [0]

      

0


source







All Articles