javascript - Centering div margin top and margin bottom -


i'm trying margin-top , margin-bottom center <div>. javascript, wrote, works. however, if site cached once, ctrl+f5 refresh causes script receive wrong clientheight. refreshing second time, retrieves correct clientheight.

i've tried using window.load , works. however, slow <div> loads , after 2 seconds, shifts middle.

<script type="text/javascript">   var height = $(window).height();   var clientheight = document.getelementbyid('account-wall').clientheight;   var calc_height = (height - clientheight) / 2;   document.getelementbyid("account-wall").style.margintop = calc_height + 'px';   document.getelementbyid("account-wall").style.marginbottom = calc_height + 'px'; </script>   <script type="text/javascript">   $(window).load(function() {     var height = $(window).height();     console.log(height);     var clientheight = $('.account-wall').height();     console.log(clientheight);     var calc_height = (height - clientheight) / 2;     document.getelementbyid("account-wall").style.margintop = calc_height + 'px';     document.getelementbyid("account-wall").style.marginbottom = calc_height + 'px';   }); </script> 

use resize event since need centered if window.height changes. make sure centered beggining use .resize() trigger event.

$(window).on('resize', function(event){   var height = $(window).height();   console.log(height);   var clientheight = $('.account-wall').height();   console.log(clientheight);   var calc_height = (height - clientheight)/2;   document.getelementbyid("account-wall").style.margintop = calc_height+'px';   document.getelementbyid("account-wall").style.marginbottom =         calc_height+'px'; }).resize(); 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -