Get a free trial // Grow your CSS skills // Land your dream job

Script randomly not running

  • # June 19, 2013 at 10:06 pm

    I have a jquery script that centers my logo on the middle of the screen. It is set up to run on page load and window resize. It works every time on window resize, and 9 times out of 10 on load. But once in a while it completely fails to run on load.
    Here’s my []( “Website”)


    # June 19, 2013 at 10:08 pm

    And the script in question:

    var height = $(‘#logo’).height();
    $(‘#logo’).css(‘margin-top’, + height / -2 + ‘px’);

    # June 19, 2013 at 10:16 pm

    that code is running on resize but not on page load.
    the time this code is executed it hasnt a reference in #logo ,on resize it has because the html has been parsed,

    enclose your code in a $(your code) is the same as writing


    var height = $(‘#logo’).height();
    $(‘#logo’).css(‘margin-top’, + height / -2 + ‘px’);

    # June 19, 2013 at 10:25 pm

    Thanks for the suggestion! It works fine the vast majority of time, but once in a while it still fails to work. Any more suggestions?

    # June 20, 2013 at 3:48 am

    Try to wait like 10ms before calling `resize()`

    setTimeout(function() {
    }, 10);

    # June 20, 2013 at 12:14 pm

    Is `#logo` an image? If so, you’ll need to wait for the image to fully load before you can calculate its height.

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed