Why is my directive getting an "empty" bounding click for el [0]?

I am writing a directive that tries to place an element that has been added to the body of the page below the element that the directive is used on. My research would show that by getting the actual top and left element that I want to display, I can use el[0].getBoundingClientRect()

, however, when I use this in a directive, I get an "empty" link reference (all properties are set to 0). Just to make sure I did console.log(el[0])

in the directive and then manually select the same item in the console window to compare them and see if I can get the Bounding Rect in the console window, which I could do. Here are the relevant console lines:

From the directive:

console.log(el[0]);
-> <div tabindex="1" class="form-control border-radius ng-binding ng-isolate-scope" time-for="schedule.monday.startTime" id="div">​1:29 PM​</div>console.log(el[0].getBoundingClientRect());
-> ClientRect {height: 0, width: 0, left: 0, bottom: 0, right: 0…}

      

On the console:

document.getElementById("div");
-> <div tabindex="1" class="form-control border-radius ng-binding ng-isolate-scope" time-for="schedule.monday.startTime" id="div">​1:29 PM​</div>document.getElementById("div").getBoundingClientRect();
-> ClientRect {height: 34, width: 90, left: 618, bottom: 347, right: 708…}

      

Is there any reason I can't get the correct rectangle reference in the directive that is obvious?

+3


source to share


1 answer


getBoundingClientRect

returns zero if the element or one of its ancestors has a style display: none

. You can use visibility: hidden

to hide it but get the appropriate size.

Also, if you have placed elements inside your element, the height can be zero.



console.log(document.querySelector('#a').getBoundingClientRect());
console.log(document.querySelector('#b').getBoundingClientRect());
console.log(document.querySelector('#c').getBoundingClientRect());
console.log(document.querySelector('#d').getBoundingClientRect());
      

see console

<div id="a" style="display: none;">hidden bits</div>
<div style="display: none;">
    <div id="b">hidden bits</div>
</div>
<div id="c" style="visibility: hidden;">hidden bits</div>
<div id="d" style="">
    <div style="float: left;">floated</div>
    <div style="float: left;">floated</div>
</div>
      

Run code


+4


source







All Articles