2

I have several <p> elements inside a <div>. The <div> has overflow-y:auto; which is hiding some <p> elements from view unless you scroll down. See http://jsfiddle.net/qnuxs/1/

How can i write a jQuery selector that only select <p> elements that are fully(not partially) visible and not hidden from view with overflow.

So from the jsfiddle example i provided the selector should give me the first 2 <p>'s (000 and 111) since they are the only tags fully in view.

Note: not all <p> tags necessary have the same height. Height can vary.

2
  • They won't be the two things visible in every case. What if the text size is messed with? Commented Mar 13, 2011 at 4:28
  • 2
    @bolt I want to select the p's that are fully in view. If none are fully in view then selector will return nothing. Commented Mar 13, 2011 at 4:29

2 Answers 2

6

You can do it, for example using your own .filter() function:

var st = $('div').scrollTop(),
    sh = $('div').height(),
    sb = st + sh - 1;

$('p').css({
    background: '#ccc'
});
$('p').filter(function() {
    var $this = $(this),
        h = $this.height(),
        t = $this.position().top,
        b = t + h - 1;
    return (t >= st && b <= sb);
}).css({
    background: 'red'
});

See DEMO: http://jsfiddle.net/qnuxs/3/

Every five seconds it makes the visible paragraphs red. It waits 5 seconds so you could scroll and see that the remaining paragraphs was not red.

Another DEMO: http://jsfiddle.net/qnuxs/4/

This version updates the colors while you scroll.

Note that the calculations seem to be incorrect so it's few pixels off but it should be enough to get you started. You probably need to use .innerHeight() for the div or maybe change something else but this is the idea: get the scroll position and div height to calculate top and bottom of visible part, and compare those values with top and bottom coordinates (relative to div) of every paragraph, and make your filter select only those within the correct range.

Sign up to request clarification or add additional context in comments.

Comments

5

Here's the core of it:

http://jsfiddle.net/qnuxs/5/

Edit: I was going to flesh it out more but rsp beat me too it.

2 Comments

Thanks +1. I felt more comfortable with your example.
Thanks and Update version to solve javaScript error: jsfiddle.net/qnuxs/118

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.