Scenario:
Sometimes u have an image tag in youre html file that is VERY big, and u want to read the height, width or something else in youre javascript.
You create a nice onload function that triggers when the dom is loaded.
You didnt set the width and height attribute in the image tag because u want it to be just as big as it is.
This specific prototype function tries to read the height: “$(‘someimage’).getHeight()” but what the f… :
height is 0, nothing or undefined????
The main problem is that you cant get some of the dom-object properties when the image has not been fully loaded.
The fix for this is to use the function onload for the image.
Create the onload event trigger:
document.getElementById('youreimageid').onload = function(){
//youre code when youre done
alert('image loaded');
}
We could make a function that returns the width and height of an image, that nicely waits till it’s loaded.
function imageDimensions(elementId){
//what to do if the image is loaded?
document.getElementById(elementId).onload = function(){
//now you can access:
var width = youreimage.width;
var height = youreimage.height;
var returnObject = {};
returnObject.width = width;
returnObject.height = height;
return returnObject;
}
//what to do if there is a error
youreimage.onerror = function(){
alert('Image '+imageSource+' could not be loaded...');
}
}
Use it like this:
var imagedimensions = imageDimensions('myimageid');
alert(imagedimensions.height);
alert(imagedimensions.width);
Soon I will introduce a full dom image preloader
Feel free to ask some questions.