Search code examples
javascriptjqueryviewportgetboundingclientrect

Get element id's within viewport


I have an iframe added inside a div tag. Iframe content has tag "sec" with specific id, like,

<p>
<sec id='1'>some text</sec>
<sec id='2'>some other text</sec>
</p>

Iframe content spreads horizontally using column width and column gap. Div is scrollable as per the iframes width.

What I need to find is the first and last id value of 'sec' tag which is visible in viewport currently.

I found about getBoundingClientRect but not clear on how it can be used?

Also the concern is that will it not increase processing load since we need to run a loop to check for each tag position?

Can anyone shade some light on it?


Solution

  • Here's how you can get the id of the first and last visible element inside an iframe, using jQuery.isInView:

    var $iframe = $( yourIframeSelector ),
        _document = $iframe[0].contentDocument,
    
        $elements = $( yourElementSelector, _document ),
        $visible = $elements.inView( _document ),
    
        firstId = $visible.first().attr( "id" ),
        lastId = $visible.last().attr( "id" );