8

Is there a way to determine whether elementA is "behind" another element and thus elementA would not be visible to the user?

Obviously it's possible to do with stacking context, but the thing is that we do not know which elements we should be looking at. Therefore we would have to iterate through all the elements in DOM and perform stacking context comparison for multiple elements. That is not good in terms of performance.

Here's a jsfiddle. So is there a way to determine that #hidden-element is not visible to the user, because another element is rendered on top of it?

https://jsfiddle.net/b9dek40b/5/

HTML:

<div id="covering-element"></div>
<div>
  <div id="hidden-element"></div>
</div>

Styles:

#covering-element {
  position: absolute;
  width: 100px;
  height: 100px;
  background: darksalmon;
  text-align: center;
}

#hidden-element {
  width: 25px;
  height: 25px;
  background: deeppink;
}
niklas-e
  • 418
  • 5
  • 11

1 Answers1

9

Our solution was to use couple things to determine whether the element is visible and not behind any other elements. Here's the methods we used.

  1. window.getComputedStyle to check visibility:hidden and display:none
  2. document.elementFromPoint from multiple points. Most common cases could probably be handled by checking all the corners. Though we needed more points to get more robust results. Corner coordinates can be easily checked with Element.getBoundingClientRect()

https://jsfiddle.net/k591Lbwu/27/

HTML

<div id="covering-element"></div>
<div>
  <div id="hidden-element"></div>
</div>

<button style="margin-top:100px">Check visibility</button>

CSS

#covering-element {
  position: absolute;
  width: 100px;
  height: 100px;
  background: darksalmon;
  text-align: center;
}

#hidden-element {
  width: 25px;
  height: 25px;
  background: deeppink;
}

JavaScript

document.querySelector('button').addEventListener('click', function() {
    const element = document.getElementById('hidden-element')
  alert('Visible = '+isVisible(element))
})

function isVisible(element) {
  if(!isVisibleByStyles(element)) return false
  if(isBehindOtherElement(element)) return false
  return true
}

function isVisibleByStyles(element) {
    const styles = window.getComputedStyle(element)
  return styles.visibility !== 'hidden' && styles.display !== 'none'
}

function isBehindOtherElement(element) {
  const boundingRect = element.getBoundingClientRect()
  // adjust coordinates to get more accurate results
  const left = boundingRect.left + 1
  const right = boundingRect.right - 1
  const top = boundingRect.top + 1
  const bottom = boundingRect.bottom - 1

  if(document.elementFromPoint(left, top) !== element) return true
  if(document.elementFromPoint(right, top) !== element) return true
  if(document.elementFromPoint(left, bottom) !== element) return true
  if(document.elementFromPoint(right, bottom) !== element) return true

  return false
}
niklas-e
  • 418
  • 5
  • 11