On a recent little project I've come across something interesting and frustrating. Say you have the following code inside a script tag within the head tag.
The first time the page loads it will alert 0, but if you reload the page it'll give you the correct width of that image. I've also tried the alternative technique below.
I get the same results. This gets quite frustrating when you're centering the image on the screen and getting zero widths and heights for the image as you can imagine. So far the only way I've been able to get the images to center without a reload is to do getElementById on it a "moment" later and adjust the style attributes (using the now accessible width/height) of the image at that point.
Though I have a working solution (at least I think it is), I was curious if other people had thoughts on the subject and maybe better solutions they'd like to share. PHP handles this stuff nicely, but prefer not to do an AJAX call. I want pure JavaScript with maybe a hint of CSS if need be.
Code:
var a = document.createElement('img');
a.setAttribute('src', 'image.png');
alert(a.width);
Code:
var a = new Image();
a.src = 'image3.png';
alert(a.width);
Though I have a working solution (at least I think it is), I was curious if other people had thoughts on the subject and maybe better solutions they'd like to share. PHP handles this stuff nicely, but prefer not to do an AJAX call. I want pure JavaScript with maybe a hint of CSS if need be.