javascript - Wrong dimensions retrieved from div on first page load -
i using robotto monospace font , need calculate single characters width.so doing
var singlecharacterwidth; function calculatecharacterswidth() { var x = $('<div>').text('a').appendto('#hiddenview'); singlecharacterwidth = x.width(); $('#hiddenview').empty(); } $(document).ready(function() { calculatecharacterswidth(); console.log(singlecharacterwidth); });
#hiddenview { float: left; font-family: 'robotomono-regular'; font-size: 12px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <link href="https://fonts.googleapis.com/css?family=roboto+mono" rel="stylesheet"> <div id="hiddenview"></div>
when page loads first time gives wrong width , after reloading page gives proper width.
first time page loading calculatecharacterswidth()
gives 9
. on reload gives proper character width i.e 7.20
what's wrong this?
screenshot of console
this doesn't happen when use default monospace font.it returns same width.
so related loading of custom font..
possible duplicate of post : jquery width() incorrect after document ready?
the idea move function call $(window).load() event instead of document ready !
it solved issues many times, hope it'll you
Comments
Post a Comment