Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all elements in viewport Javascript

I wonder if it is possible (in javascript or jquery but without any plugins) to get all elements (for example table rows tr) in current viewport without looping through each of them? I found a lot of examples how to check if specified element is in current viewport, but what I need is a function returns a list of all elements in current viewport. I need this for virtualization because this table should have an infinite capacity and looping through each row from two millions rows is quite inefficient :)

Is there any reasonable way to do this?

like image 800
Adam Mrozek Avatar asked Jun 27 '14 12:06

Adam Mrozek


People also ask

How do you get the elements from the viewport?

Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.

Is element in viewport Javascript?

If an element is in the viewport, it's position from the top and left will always be greater than or equal to 0 . It's distance from the right will be less than or equal to the total width of the viewport, and it's distance from the bottom will be less than or equal to the height of the viewport.

Is element in viewport jQuery?

Check if element is visible in viewport using jquery: If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially).

How do we make an element always visible on the browser window?

You need to put position: fixed; on the div element. That will anchor it to the viewport.


1 Answers

Assuming you're not doing anything fancy with positioning, table rows in the viewport can be found with a binary search. For example, for 200000 rows, about 18 lookups are required to locate the first row on the page (jsfiddle, warning: slow to load). This can be extended to find the last element as well, or you could just loop through the elements starting from the first until you find one that is no longer visible.

var rows = table.children().children();
var start = 0;
var end = rows.length;
var count = 0;

while(start != end) {
    var mid = start + Math.floor((end - start) / 2);
    if($(rows[mid]).offset().top < document.documentElement.scrollTop)
        start = mid + 1;
    else
        end = mid;
}

Obviously this does not work well if anything is floated, absolutely positioned, etc. In short: The nodes being searched must be in order such that rows[N-1].top <= rows[N].top. For something such as a table, this should be true if no styling is applied and no multi-row cells exist.

like image 197
Dark Falcon Avatar answered Oct 12 '22 20:10

Dark Falcon