Javascript: Geting image width from a newly created object

From Urandom
Jump to: navigation, search

In a web page, I had to set the image marginLeft style attribute when creating new images to a page. The problem was that the margin-left was related to the images width (had to set it to half of the image width).

This did not work:

var i=document.createElement('img');

However it worked after a refresh of the page, the browser had then loaded the image itself and only then is the Image.width parameter available. To get around this I used this trick:

var i=document.createElement('img');
i.onload=new Function("'px';");
Personal tools