Reputation: 308
I've created a simple modal window to a large version of a thumbnail, to position the image centre screen I need the image size. I've tried .load but can't seem to get anything to work - on the second click it works OK as the image as been loaded, unfortunately with a width and height of 0.
$(function(){
$(".quickImg").click(function(){
var imageSrc = 'images/'+$(this).attr('rel')+'/'+$(this).attr('href').replace('#', '')+'_full.jpg';
var imgSize = new Image();
imgSize.src = imageSrc;
IMAGE LOADING HERE
var imgW = imgSize.width,imgH = imgSize.height;
var imgDiv='<div id="qrBlock"></div><div id="newsModal" style="margin-left:-'+imgW/2+'px;margin-top:-'+imgH/2+'px"><a href="#" title="Close Window" class="closeQR">X</a><img src="'+imageSrc+'" width="'+imgW+'" height="'+imgH+'" /></div>'
$('body').append(imgDiv);
});
});
Upvotes: 0
Views: 67
Reputation: 3625
You should wait for image to load to get its width and height. To do that first you have to attach onload
event to an image and a callback to execute when image is loaded:
$(function(){
$(".quickImg").click(function(){
var imageSrc = 'images/'+$(this).attr('rel')+'/'+$(this).attr('href').replace('#', '')+'_full.jpg';
var imgSize = new Image();
imgSize.onload = function(){
var imgW = this.width,
imgH = this.height,
imgDiv = '<div id="qrBlock"></div><div id="newsModal" style="margin-left:-'+imgW/2+'px;margin-top:-'+imgH/2+'px"><a href="#" title="Close Window" class="closeQR">X</a><img src="'+imageSrc+'" width="'+imgW+'" height="'+imgH+'" /></div>';
$('body').append(imgDiv);
}
imgSize.src = imageSrc;
});
});
Upvotes: 1