2

I have a script that calculates the height of a div and returns it as a style. But when you rotate mobile-devices the height changes, so I need a way to reload it. How can I accomplish this?

<script type="text/javascript">
window.onload = function() {
    var height = document.getElementById('id').offsetHeight;
    document.getElementById('id').style.marginTop = height + 'px';
}
</script>
Linger
  • 14,942
  • 23
  • 52
  • 79
nicolas
  • 2,560
  • 2
  • 17
  • 16

2 Answers2

4

Make a function out of it and call that on both load and resize. No need to reload your page, just call the code again:

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

window.onload = calcHeight;
window.resize = calcHeight;

</script>
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • It works in cases like `alert("resize event detected!");` but not for my script. Why? – nicolas Sep 07 '12 at 14:33
  • @nicolas - Perhaps you need to reset the marginTop back to it's default value (like it was when the page was loaded) before getting the offsetHeight. There's probably a better way to do what you're trying to do, but without seeing the HTML, we can't advise on that. – jfriend00 Sep 07 '12 at 22:42
3

You can create a function:

function setHeight() {
   var height = document.getElementById('id').offsetHeight;
   document.getElementById('id').style.marginTop = height + 'px';
}

That you can call onload:

window.onload = function() {
   setHeight();
   // Other actions when window is loaded
}

And onresize:

window.onresize = function(event) {
   setHeight();
   // Other actions when window is resized
}

This should do the job.

Catalin MUNTEANU
  • 5,618
  • 2
  • 35
  • 43