I’ve just noticed that at some stage Chrome has updated to a new version and some of my jQuery code no longer works… (jQuery version 1.7 – bundled with wordpress)
This is basic code for positioning images (centring) in a slide show and positioning the previous / next buttons.
It works in FF (don’t know about IE – I look at that as little as possible). What it now does in chrome, instead of doing the calculation of height of box minus height of image, is to simply divide the box height by two. So, whereas for a box 4x high with an image 2x high FF gives me the correct “top: 1x”, Chrome gives me “top:2x”.
Strangely it positions the #next and #prev divs correctly…
h = j$('.slide').height();
w = j$('.slide').width();
nph = j$('#next').height();
j$('.slide').each(function(){
thisImg= j$(this).find('img');
var imgH = thisImg.height();
var imgW = thisImg.width();
thisImg.css({'position':'absolute',
'top':(h-imgH)/2,
'left':(w-imgW)/2
} );
}) ;
j$('#next, #prev').css('top',(h-nph)/2);
};
Either I’m not doing something correctly, or something has changed in chrome (I’ve lost a complete animation on another site since the update).
If I’m not at fault, what hack is there for Chrome?
EDIT Further research leads me to think it is because I am trying to use images in a flexible (percentage based) environment.
This means the image and the div are styled thus :
div {height:100%;width:100%;}
img {max-height:100%;max-width:100%}
It seems that Firefox can make the calculation, but Chrome can’t. The “next” and “prev” divs have known dimensions (and position correctly) Is there a way of “catching” the image as it is loaded and finding out what it’s dimensions are before max-height and max-width are applied ?
FURTHER UPDATE
I have managed to confirm that Chrome cannot return the value of the height of an image on the page if it’s styled “max-height” or “max-width”. Nor does the “outerHeight/Width” method work.
Nick, I think the workaround is to apply the
max-heightandmax-widthlimits in javascript rather than CSS with the added advantage of allowing the images’ aspect-ratio to be maintained. The CSS does not have this feature as it applies the height and width limits independently.Applying the limits can be done in the same loop that applies the ‘left’ and ‘top’ offsets.
Try this:
As indicated in the comment, I had to assume that
.slideis the constraining wrapper. If not, then adjust the selector in the statement$wrapper = $img.closest(".slide").Don’t worry about
Math.min(), it’s not a mistake. Taking a minimum , applies a maximum.