Skip to main content

Check if an element is visible in the browser viewport.

/**
 * Returns true if the element specified is visible in the viewport, false
 * otherwise.
 *
 * @param {Element} el The element to determine if it visible within the current
 *     browser viewport.
 * @param {Boolean} [partiallyVisible] Omit this argument to determine if the
 *     element is entirely visible, or specify true to determine if it is
 *     partially visible.
 * @return {Boolean} Returns true if the element specified is visible in the
 *     viewport, false otherwise.
 *
 * @see https://www.30secondsofcode.org/snippet/elementIsVisibleInViewport
 */
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
  const { top, left, bottom, right } = el.getBoundingClientRect();
  const { innerHeight, innerWidth } = window;

  return partiallyVisible
    ? ((top > 0 && top < innerHeight) ||
        (bottom > 0 && bottom < innerHeight)) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
    : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};

// ES5 version:
var elementIsVisibleInViewport = function(el, partiallyVisible) {
  if (partiallyVisible === void 0) {
    partiallyVisible = false;
  }

  var _a = el.getBoundingClientRect(),
    top = _a.top,
    left = _a.left,
    bottom = _a.bottom,
    right = _a.right;

  var innerHeight = window.innerHeight,
    innerWidth = window.innerWidth;

  return partiallyVisible
    ? ((top > 0 && top < innerHeight) ||
        (bottom > 0 && bottom < innerHeight)) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
    : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};

//
// Examples:

// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
elementIsVisibleInViewport(el); // false - (not fully visible)
elementIsVisibleInViewport(el, true); // true - (partially visible)