6

How can I get the first DOM element that is visible in a viewport?

PS: the first DOM element in a page will not be the first "visible" element when I scroll to the middle or bottom of the page

rajeemcariazo
  • 2,476
  • 5
  • 36
  • 62

2 Answers2

4

In mind with the scroll, you'll need to query the whole document, get the elements offset positions, and match that agains the scrollTop value of the window. Then query the :eq(0) (jQuery) of those.

EDIT: I think this sample will work, haven't tried it out yet tho, since I'm unable to access any fiddle here at work computers.

$(function () {
    var scroll = $(window).scrollTop();
    var elements = $("*"); // VERY VERY bad performance tho, watch out!
    var el;
    for (var i=0; i<elements.length; i++) {
        el = $(elements[i]);
        if (el.offset().top >= scroll && el.is(':visible')){
            // "el" is the first visible element here!
            // Do something fancy with it

            // Quit the loop
            break;
        }
    }
});
Eric
  • 18,532
  • 2
  • 34
  • 39
  • I'm testing your code, sorry for this novice question: why do I have to enclose all with a jquery function, and also why do I have to do this: el = $(elements[i]); instead of this: el = elements[i] – rajeemcariazo Jul 29 '13 at 10:27
  • 1
    The jQuery function is just a short-hand for `$(document).ready()`. And I think you can do `el = elements[i]` directly yes, I wasn't really sure, therefore I played safe (since I cannot debug it myself) – Eric Jul 29 '13 at 10:32
  • I'm using this, but it tends to be slow if you have a lot of elements to loop through. Would this be possible any other way? – jmchauv Feb 18 '19 at 20:51
  • A way to improve performance would be to loop over the elements in steps of 3 or 5 and if an element is on the viewport, go back to the previous third/fifth element and check every one from there on. – swift-lynx Apr 04 '21 at 16:48
0
$(function () {
    var $sections = $(".main > section");
    var idxCurSection = -1; // Index of first visible section
    var scroll = $(window).scrollTop();
    var el;
    for (var i = 0; i < $sections.length; i++) {
        el = $($sections[i]);
        if (el.offset().top >= scroll && el.is(':visible')) {
            idxCurSection = i;
            break;
        }
    }
    if (idxCurSection === -1)
        idxCurSection = $sections.length - 1;

    alert("Index of first visible section: " + idxCurSection);
});
Dmitry Shashurov
  • 1,148
  • 13
  • 11