Andrew
Andrew

Reputation: 238717

How to select elements within boundary?

I'm trying to figure out a way to select elements that are overlapped (and contained, completely covered up) within an absolutely positioned div.

I basically need to select elements within a certain pixel boundary. How can this be done using jQuery?

Upvotes: 3

Views: 261

Answers (2)

cambraca
cambraca

Reputation: 27835

Suppose your html is something like:

<div id="thediv"></div>
<div id="one">one</div><br />
<div id="two">two</div><br />
<div id="three">three</div><br />

You could have this jQuery:

$('div:not(#thediv)').filter(function() {
    var offset = $(this).offset();
    var left = offset.top;
    var top = offset.top;
    var right = left + $(this).width();
    var bottom = top + $(this).height();

    var offset2 = $('#thediv').offset();
    var left2 = offset2.top;
    var top2 = offset2.top;
    var right2 = left2 + $('#thediv').width();
    var bottom2 = top2 + $('#thediv').height();

    if (
        (
            (left < left2 && right > left2)
            || (left > left2 && right < right2)
            || (left < right2 && right > right2)
        )
        &&
        (
            (top < top2 && bottom > top2)
            || (top > top2 && bottom < bottom2)
            || (top < bottom2 && bottom > bottom2)
        )
        )
        return true;
    else
        return false;
}).css('background-color', 'red');

And the divs that overlap with the main div would turn red. You can test it here.

The idea is to get the offset(), width() and height() of the elements, and see if they overlap. The code is probably not very efficient, I wrote it like this to make it clear.

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219938

Here's the basic idea:

var left = 100,
    top = 200,
    right = 300,
    bottom = 500;

$('#main-div').children().filter(){
    var $this = $(this),
        offset = $this.offset(),
        rightEdge = $this.width() + offset.left,
        bottomEdge = $this.height() + offset.top;

    if (offset.top > top && offset.left > left && right > rightEdge && bottom > bottomEdge) {
        return true;
    }

    return false;
});

Change the coordinates at the top to whatever you need.

Upvotes: 2

Related Questions