maxkoshel
4/26/2017 - 10:34 AM

Find out which element is the most visible

Find out which element is the most visible

function getMostVisibleElement (els) {

  var viewportHeight = window.innerHeight

  var max = 0
  var mostVisibleEl = null

  for (var el of Array.from(els)) {

    var rect = el.getBoundingClientRect()
    var height = rect.bottom - rect.top
    var visible = {
      top: rect.top >= 0 && rect.top < viewportHeight,
      bottom: rect.bottom > 0 && rect.bottom < viewportHeight
    }

    var visiblePx = 0
    if ( visible.top && visible.bottom ) {
      visiblePx = height // Whole element is visible
    } else if ( visible.top ) {
      visiblePx = viewportHeight - rect.top
    } else if ( visible.bottom ) {
      visiblePx = rect.bottom
    } else if ( height > viewportHeight && rect.top < 0 ) {
      var absTop = Math.abs( rect.top )
      if ( absTop < height ) {
        visiblePx = height - absTop // Part of the element is visible
      }
    }

    if ( visiblePx > max ) {
      max = visiblePx
      mostVisibleEl = el
    }

  }

  return mostVisibleEl

}