Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: get elements above a given 'y' position

How can you do this with jQuery, in an elegant way?

Apply z attribute (e.g.: red background) to every children of a div parent
while their position is above a given top-offset y.

I've tried in different ways, but I'm not happy with any of them...
I know there must be a short and elegant way to do it...

like image 745
dolma33 Avatar asked May 23 '26 12:05

dolma33


2 Answers

Since you're saying you've tried a few ways, and you're just looking for something more elegant, I'll assume you have the offset part worked out, and I'll just go with offset myself. Modify that part as needed. For elegance, you could create a custom selector checking top offset:

$.expr[':'].above = function(obj, index, meta, stack) { 
    return $(obj).offset().top < meta[3];
}

You could then query it as such:

$('#myParentDiv').find('div:above(100)').css('background-color', 'red');

Of course this could just as well have been expressed as

$('#myParentDiv div:above(100)').css('background-color', 'red');

or, as pointed out in comments

var y = 100;
$('#myParentDiv div:above('+y+')').css('background-color', 'red');
like image 195
David Hedlund Avatar answered May 25 '26 10:05

David Hedlund


Something like this should get the job done:

var y = 250,
    RED = '#F00';

$('#parent > *').css('background-color', function (i, v)
{
    if ($(this).offset().top < y)
    {
        return RED;
    }
    return v;
});

The selector '#parent > *' will select all immediate children (not all descendants) of the element with id parent. I assume that's what you're looking for, since you said "apply... to every children of a div parent."

Demo: http://jsfiddle.net/mattball/87QFU/1/

like image 30
Matt Ball Avatar answered May 25 '26 08:05

Matt Ball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!