What's the right way to run a javascript function without getting the object to "jump" right after the page loads -


i have simple page object gets "top" property javascript.

how run function without getting things on page "jump" ?

  <script type="text/javascript">      function changeheight () {     //gets height     var h = window.innerheight;     //alert(h);     console.log(h);      var categories = document.getelementbyid("cat").offsetheight;      //alert(categories);      var x = 0.32 * categories;         var cattop =  h - x;         //gets cats       document.getelementbyid("cat").style.top = cattop+"px";     }      </script>  </head> <body onload="changeheight()" onresize="changeheight()">   <div class="main">      <div class="cat" id="cat"></div>  </div>   </body> </html> 

i used "onload" on tag run function. know that's not good.

the object jumps because move after dom has been rendered. that's onload does: make sure dom complete , loading/rendering has happened.

there 2 solutions:

  1. put script element after node.
  2. use css position element

the first solution looks this:

<div class="main">      <div class="cat" id="cat"></div>     <script>...</script>  </div> 

at time when script executed, necessary dom nodes there. unless layout complex, offsets should correct @ time. note many browsers start rendering while page loading. there still might jump less often, depending on complexity of page, browser optimizations, etc.

the second solution wrap element in container set margin/padding until cat element naturally positioned correctly. 0.32 translated 32%. need element around has correct height isn't visible.

to final solution should give body height: 100%, add 2 containers inside. 1 content , other position cat element. need play position style. then

#cat { top: 32% } 

should trick.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -