CRAIG
CRAIG

Reputation: 1029

Reported height of DIV is changing upon refresh with Javascript/Jquery

I have a bit of Javascript calculating the position of a certain DIV. This JS is within some other JS and jQuery within a document.ready.

Here is the HTML.

<div id="outer-box">
    <table id="text-preview">
        <tr>
            <td>
                TESTING THIS.
            </td>
        </tr>
    </table>
</div>

Here is the javascript:

var element = document.getElementById('text-preview');
var positionInfo = element.getBoundingClientRect();

var outerelement = document.getElementById('outer-box');
var outerpositionInfo = outerelement.getBoundingClientRect();
var outerheight = outerpositionInfo.height;
var textpreviewheight = positionInfo.height;

What I am finding is, on first load, the var textpreviewheight is 94.

When I refresh the page it is 62.

If I clear cookies it goes back to 94.

The ACTUAL height is 62.

Maybe I am just not fully understanding how cookies work with JS, but is there something specific I should be looking for in this case?

Upvotes: 2

Views: 1220

Answers (1)

Udochukwu Enwerem
Udochukwu Enwerem

Reputation: 2823

Try using $(window).on('load') instead of $(document).ready() when you need to read UI component values. That way, you ensure the entire window UI is fully loaded (not only ready) before reading the component value.

I think the final value of 62 is the actual height after the window is fully loaded. 94 is height just immediately after the DOM is ready. The discrepancies may be as a result of interaction with other UI components before a full load of the page.

<body>
<div id="outer-box">
    <table id="text-preview">
        <tr>
            <td>
                TESTING THIS.
            </td>
        </tr>
    </table>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>

<script>
    $(window).on('load', function() {
        var element = document.getElementById('text-preview');
        var positionInfo = element.getBoundingClientRect();
    
        var outerelement = document.getElementById('outer-box');
        var outerpositionInfo = outerelement.getBoundingClientRect();
        var outerheight = outerpositionInfo.height;
        var textpreviewheight = positionInfo.height;
        console.log(textpreviewheight);
    });
</script>
</body>

Upvotes: 1

Related Questions