nicolas
nicolas

Reputation: 2660

Calculate div height and return as margin?

I'm trying to make a script that calculates the height of a div 'id' and returns the same value as margin-top. But this doesn't do it. What's wrong?

<script language="text/javascript">
var height = document.getElementById('id').innerHeight;
document.getElementById('id').style.marginTop = height + 'px';
</script>

Thanks in advance!

Upvotes: 2

Views: 150

Answers (3)

Er. Anurag Jain
Er. Anurag Jain

Reputation: 1793

First error in your js is language="text/javascript" it must be type="text/javascript". and try to use offsetHeight in place of innerHeight

  <script type="text/javascript"  >

        var height = document.getElementById('id').offsetHeight;
        document.getElementById('id').style.marginTop = height + 'px';
        }
  </script>

And call it onload event.

thanks ,

Upvotes: 0

Alfred
Alfred

Reputation: 21406

Try;

<script type="text/javascript">
window.onload = function() {
var height = document.getElementById('mydiv').offsetHeight;
document.getElementById("mydiv").style.marginTop = height+'px';
}
</script>

Here is a live demo.

Upvotes: 2

Luca Matteis
Luca Matteis

Reputation: 29267

Remember that you should only manipulate the DOM after the onload event is fired, or for modern browsers when the DOMContentLoaded event is fired. Anyhow, onload will work just fine for your case.

Try:

<script language="text/javascript">
window.onload = function() {
    var height = document.getElementById('id').innerHeight;
    document.getElementById('id').style.marginTop = height + 'px';
}
</script>

Upvotes: 2

Related Questions