Search code examples
javascripthtmlcsspositionfixed

Calculating "left" and "top" value from fixed positioned floating element


The following is my code:

HTML:

<div id="test">
This text is fixed in one spot
</div>

CSS:

#test{
    border:1px solid black;
    position: fixed;
    margin: 8px;
    right: 0px;
    bottom: 0px;
    height: 200px;
    width: 50%;
    z-Index: 4;
}

So far I am able to make a box in a fixed position and have it display properly (height 200 pixels and width 50 percent of the screen). The width changes when the screen width changes, but the problem I have is that I want to calculate the top-left pixel position of the box because I don't want any part of the box to appear on top of any adsense ad unit. I have my ad units on the left-side of the screen.

I tried in javascript by obtaining values of the left-most pixel of the box like this:

<script>
alert(document.getElementById('test').left);
alert(document.getElementById('test').style.left);
</script>

And I did not get a number from either message box. All I got was a blank and "undefined".

Is there a way the top-left pixel position of the box can be calculated without forcing a value on regular intervals through a javascript timer?

And no, I don't want to use Jquery.


Solution

  • I think what you are looking for is offsetLeft and offsetTop methods.

    alert(document.getElementById('test').offsetLeft);
    alert(document.getElementById('test').offsetTop);
    #test{
        border:1px solid black;
        position: fixed;
        margin: 8px;
        right: 0px;
        bottom: 0px;
        height: 200px;
        width: 50%;
        z-Index: 4;
    }
    <div id="test">
    This text is fixed in one spot
    </div>