Search code examples
javascriptjqueryhtmlmultiple-columns

How to get first visible DOM element currently showing on the screen?


How to get first visible DOM element currently showing on the screen ?

I tried something like

var el = document.elementFromPoint(x, y) 

and increasing the y coordinates in a while loop, but the problem is it does not work when there are CSS multi columns on the document, in that case the <html> tag is returned, not the actual element.

Is there any way I can really get the element on the top-left of the screen which works for CSS columns?


Solution

  • This is a very basic example that just gets the element that is the furthest to the top. It's just a start, because you may want to take into consideration the left offset as well.

    You'll want to exclude the body and html elements (as shown below), since they will always be first.

    Fiddle

    var first;
    $(':visible').not('body, html').each(function() {
        if (typeof first == 'undefined') {
            first = $(this);
        } else if ($(this).offset().top < first.offset().top) {
            first = $(this);
        }
    });
    first.addClass('highlight');