Skip to Content

isInView()

Check if an element is within the current viewport (even partially).

JavaScript July 2, 2019

Usage

JavaScript
nebula.isInView(element, offset)

Parameters

element
(Required) (String or Object) A selector or jQuery object if the element to check
Default: None

offset
(Optional) (Float) Offset the viewport height
Default: None

Parameter Notes

Use offset (for example) to trigger animations early or late. This is multiplied by the viewport bottom pixel value, so “0.33” would trigger earlier (because it “raises” the bottom thereby “shrinking” the viewport detection area). A value of 250 here would trigger early because it “lowers” the bottom of the viewport thereby “growing” the detection area.

Request or provide clarification »

Examples

JavaScript
if ( nebula.isInView(jQuery('#video')) ){
    alert('The video is in view!');
}

Offset the detection area to 33% of the actual viewport height

JavaScript
if ( nebula.isInView('#section-4', 0.33) ){
    //Trigger an animation "late" so the section is mostly in the viewport before starting the animation
}

Additional Notes

This will return true even if a sliver of the element is in the viewport. It will also work if the element extends both above and below the viewport (if it is really tall).

This function also takes into account if the current window/tab is visible (focused).

Source File

Located in /assets/js/nebula.js on line 1794.

JavaScript
nebula.isInView = function(element, offset){
    if ( element ){
        if ( typeof element === 'string' ){
            element = jQuery(element);
        }

        if ( !offset ){
            offset = 1;
        }

        var elementTop = element.offset().top;
        var elementBottom = element.offset().top+element.innerHeight();

        var windowTop = nebula.dom.document.scrollTop();
        var windowBottom = nebula.dom.document.scrollTop()+nebula.dom.window.height()*offset;

        if ( !nebula.dom.body.hasClass('page-visibility-hidden') && ((elementTop >= windowTop && elementTop < windowBottom) || (elementBottom >= windowTop && elementBottom < windowBottom) || (elementTop < windowTop && elementBottom > windowBottom)) ){
            return true;
        }
    }

    return false;
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.isInView = function(element, offset){
    //Write your own code here, leave it blank, or return false.
}