0

I hope to not confuse people but I can't figure this out. I have a lightbox script I wrote myself, and I'm trying to have the margins, height and width set up so the box is always centered vertically.

The first time I load an image, the margins do not correct and the image appears off the page. The second time it loads fine. The problem seems more consistent in Chrome (on Linux).

I'm sure there is a logic problem there somewhere so any help would be very appreciated. Thank you.

    image = lightbox.childNodes[0];

    boxHeight = window.innerHeight;
    boxWidth = window.innerWidth;
    imgHeight = image.height;
    imgWidth = image.width;

    image.style.maxHeight = (boxHeight-100)+'px';

    imgHeight = image.height;  //Do this again to correct for max height
    imgWidth = image.width;

    if(imgWidth >= (boxWidth-50) || imgHeight >= (boxHeight-50)){
        lightbox.style.width="70%";
        image.style.width = "100%";

        imgHeight = image.height;
        imgWidth = image.width;
    }

    lightbox.style.top = (boxHeight/2)+'px';
    lightbox.style.marginTop = ((-1)*(imgHeight/2))+'px';
    lightbox.style.left = (boxWidth/2)+'px';
    lightbox.style.marginLeft = ((-1)*(imgWidth/2))+'px'; 
    lightbox.style.display = 'block';
    fadeEffect.init(lightbox, 1, 100); //Fade In
Josh Dredge
  • 107
  • 1
  • 1
  • 10

1 Answers1

3

It is not working beacuse the image still not loaded fully. Change it like this:

image = lightbox.childNodes[0];

boxHeight = window.innerHeight;
boxWidth = window.innerWidth;

image.onload = function(){ // Here is the trick

    imgHeight = image.height;
    imgWidth = image.width;

    image.style.maxHeight = (boxHeight-100)+'px';

    imgHeight = image.height;  //Do this again to correct for max height
    imgWidth = image.width;

    if(imgWidth >= (boxWidth-50) || imgHeight >= (boxHeight-50)){
        lightbox.style.width="70%";
        image.style.width = "100%";

        imgHeight = image.height;
        imgWidth = image.width;
    }

    lightbox.style.top = (boxHeight/2)+'px';
    lightbox.style.marginTop = ((-1)*(imgHeight/2))+'px';
    lightbox.style.left = (boxWidth/2)+'px';
    lightbox.style.marginLeft = ((-1)*(imgWidth/2))+'px'; 
    lightbox.style.display = 'block';
    fadeEffect.init(lightbox, 1, 100); //Fade In
}

Look here , there is more conventional way: Javascript Image onload event binding
and here: JavaScript/jQuery event listener on image load for all browsers

Community
  • 1
  • 1
Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146