jqueryscrollvisible

jQuery check if element is visible inside scrollable div


Ok so I use the following code to check whether an element is visible on-screen.

(function($) {

/**
    * Copyright 2012, Digital Fusion
    * Licensed under the MIT license.
    * http://teamdf.com/jquery-plugins/license/
    *
    * @author Sam Sehnert
    * @desc A small plugin that checks whether elements are within
    *     the user visible viewport of a web browser.
    *     only accounts for vertical position, not horizontal.
 */

$.fn.visible = function(partial) {

    var $t            = $(this),
        $w            = $(window),
        viewTop       = $w.scrollTop(),
        viewBottom    = viewTop + $w.height(),
        _top          = $t.offset().top,
        _bottom       = _top + $t.height(),
        compareTop    = partial === true ? _bottom : _top,
        compareBottom = partial === true ? _top : _bottom;

  return ((compareBottom <= viewBottom) && (compareTop >= viewTop));

};

})(jQuery);

However, I would like to use this piece of code so that it checks whether it is visible inside a scrollable element. Specifically the main tag which I used for my main content. How would I go about changing this code so that it works for my scrollable element? I'm not quite sure what to do. I've already tried changing $w variable to $('main') but that seems to behave odd.


Solution

  • I know this is really old and in the time that jQuery was still a thing, but nowadays it seems that Javascript has an Intersection Observer API specifically meant for this purpose.

    See MDN: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API