Is Element Visible Percentage

This example, based on element.getBoundingClientRect() API, will return visibility properties like visible area and visible percentage of the specified DOM element.

by Slava Fomin II

HTML

<div id="draggable"></div>
<div id="info"></div>

CSS

body {
  width: 2000px;
  height: 1000px;
  overflow: scroll;
  margin: 0;
  padding: 0;
}

#draggable {
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: deeppink;
  cursor: move;
  left: 50px;
  top: 50px;
}

#info {
  position: fixed;
  width: 100%;
  height: 50px;
  background-color: #aaa;
  bottom: 0;
  left: 0;
}

JavaScript

function getElementVisibility(element) {

  const rect = element.getBoundingClientRect();
  
  const elementArea = (rect.width * rect.height);
  
  let visibleWidth = (
    rect.left >= 0 ? rect.width : rect.width + rect.left
  );
  if (visibleWidth < 0) {
    visibleWidth = 0;
  }
  
  let visibleHeight = (
    rect.top >= 0 ? rect.height : rect.height + rect.top
  );
  if (visibleHeight < 0) {
    visibleHeight = 0;
  }
  
  const visibleArea = visibleWidth * visibleHeight;
  
  return { 
    elementArea,
    visibleWidth,
    visibleHeight,
    visibleArea,
    visiblePercentage: (visibleArea / elementArea * 100)
  };
  
}



const element = document.getElementById('draggable');

let isDragging = false;

element.addEventListener('mousedown', () => {
  isDragging = true;
});

document.addEventListener('mouseup', () => {
  isDragging = false;
});

document.addEventListener('mousemove', (event) => {
  const style = element.style;
  if (isDragging) {
    style.top = event.clientY + 'px';
    style.left = event.clientX + 'px';
  }
});

setInterval(() => {
  const rect = element.getBoundingClientRect();
  const info = document.getElementById('info');
  const result = getElementVisibility(element);
  info.innerText = JSON.stringify({ rect, result });
  if (result.visibleArea > 0) {
  	info.style.backgroundColor = 'lime';
  } else {
    info.style.backgroundColor = 'red';
  }
}, 100);