Reputation: 91
I have a jQuery script that reads img height and adds style tag to head tag.
jQuery
var img = document.getElementById('logomini');
height = img.clientHeight;
$(function (){
$("<style type='text/css' id='style1'>#menu ul { line-height: "+ height +"px }</style>").appendTo("head");
});
The problem: sometimes the script is working properly and sometimes it's not. When I'm refreshing my website (Wordpress) the line-height is 80px or 0px. I think it's a problem with script loading. When script is loading faster than img it showing 0px. But it's only my guess... The script tag is right before </body>
tag.
Any ideas?
Upvotes: 1
Views: 311
Reputation: 26150
If you want to be sure the image is fully loaded first, then use this code:
/* In WordPress, $ may be used for other libraries, so use this safer "document ready" method */
jQuery(function($) {
/* wait until everything in the window has loaded */
$(window).load(function() {
var img = document.getElementById('logomini');
height = img.clientHeight;
// The above two lines could be simplified like so:
var height = $('#logomini').height();
$("<style type='text/css' id='style1'>#menu ul { line-height: "+ height +"px }</style>").appendTo("head");
});
});
Also see this answer: Delaying a jquery script until everything else has loaded
Upvotes: 2