Javascript/JQuery function not working on first page load. Then works on refresh

1.5k views Asked by At

I have a javascript function that centers a div vertically by finding the height of the parent div and its own height, then sets the correct positioning.

This function doesn't seem to work when the page is loaded for the very first time but works every time after you refresh. I call this function at the top of $(document).ready...

Any ideas?

function positionCardText() {

  $('.copyIllustration').each(function(i){
    var containerHeight = $(this).parent().height();
    var illustrationHeight = $(this).height();
    $(this).css('top', ( containerHeight/2 ) - ( illustrationHeight/2 ) );
  });

};
2

There are 2 answers

0
Tamino Martinius On

When the div contains an image - the height calculation is wrong as long the image is not loaded.

If you reload the page the image is already cached and the height can be calculated properly.

If this causes the reason, you can either add the size to the image tag or you load the script on the load callback of the image.

0
Ritesh  Karwa On

Try this

 $(document).ready(function(){
    function positionCardText() {

      $('.copyIllustration').each(function(i){
        var containerHeight = $(this).parent().height();
        var illustrationHeight = $(this).height();
        $(this).css('top', ( containerHeight/2 ) - ( illustrationHeight/2 ) );
      });

    };

    });