Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Find out the visible percentage of an obscured DOM element

Edit The following HTML and CSS are just an example, the real use-case involves a complex DOM, and should be generic enough to work on different webpages. Only valid assumption is that all elements are rectangular.


Given the following:

HTML

<div class="a" id="a">
A
</div>
<div class="b">
B
</div>
<div class="c">
  C
  <div class="d">
  D
  </div>
</div>

CSS

.a,.b,.c,.d{
  border: solid 1px black;
  opacity: 0.5;
  font-family: arial;
  position: absolute;
  font-size: 20px;
}

.a{
  width:300px;
  height:250px;
  top:30px;
  left:20px;
  background:green;
}

.b{
  width:300px;
  height:145px;
  top:10px;
  left:20px;
  background:blue;
}
.c{
  width:150px;
  height:300px;
  top:30px;
  left:60px;
  background:red;
}
.d{
  margin:10px;
  background:yellow;
  width:100px;
  height:200px
}

produces the following result:
enter image description here


I'm trying to detect the percentage of the "A" DIV that is not obscured by other elements, IE: 25% in the given example.

I've written the following JS (fiddle) that scans the rect area of the "A" DIV and collects the obscuring elements.

let el = document.getElementById("a");
let rect = el.getBoundingClientRect();
let right = rect.x + rect.width;
let bottom = rect.y + rect.height;
let elements = [];
for (let i = rect.x; i < right; i += 10) {
  for (let j = rect.y; j < bottom; j += 10) {
    let sampled = document.elementFromPoint(i, j);
    if (sampled && sampled !== el && elements.indexOf(sampled) === -1) {
      elements.push(sampled);
    }
  }
}

Now I'm trying to find the most efficient way to do the calculations. I tried another approach of scanning the rect pixel by pixel and count all pixels that are not part of the main DIV, however this approach appeared to be slow for an accepted solution.

Any help would be appreciated.

UPDATE
After doing some research, I'm starting to think I will need the sweep-line algorithm, still not exactly sure how to modify the code to fit my problem.

Update 2
When using pointer-events: none;, the document.elementFromPoint approach will not work, so I'm looking for a better solution.

like image 448
Shlomi Schwartz Avatar asked May 23 '18 11:05

Shlomi Schwartz


1 Answers

You can use the Intersection Observer to get the visible percentage of an element within a parent..

https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

It’s experimental though!

like image 167
Kokodoko Avatar answered Sep 17 '22 21:09

Kokodoko