All I need to do is locate image at the center of its parent div.
First, I tried this.
$(document).ready(function() {
$('#image1').css({
'top': 50%, 'left': 50%,
'margin-top': (-$('#image1').height()/2) + 'px',
'margin-left': (-$('#image1').width()/2) + 'px'
});
});
It failed cause $('#image1').height() and width() gives 0 before it is fully downloaded.
So I tried to keep inspecting size of the image until it has specific width and height.
like,
function inspectSize() { return ($('#image1').width() != 0); }
function setPosition() {
if(!inspectSize()) {
setTimeout(setPosition, 1000);
return;
}
$('#image1').css({
'top': 50%, 'left': 50%,
'margin-top': (-$('#image1').height()/2) + 'px',
'margin-left': (-$('#image1').width()/2) + 'px'
});
}
$(document).ready(setPosition);
Still it doesn't work.
because $('#image').width() returns 28px before it is downloaded in IE8 (by the way, IE7 was fine)
So I finally tried waitForImages jQuery plugin
like this,
$(document).ready(function() {
$('#image1').waitForImages(function() {
setPosition(); // without inspectSize()
});
});
It works fine with cached images, but doesn't work with non-cached images.
The function is called before Image1 has width and height.
What should I do?