1

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.

my demo page

Any ideas?

2
  • You are setting the height variable before the image, you're getting the height from, is loaded. You should be defining the variables within the document ready function. Commented Feb 2, 2016 at 19:51
  • well, still not working Commented Feb 2, 2016 at 20:01

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry :) well nothing changed. Still, sometimes is working properly, sometimes it's not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.