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');
i.src='sample.jpg';
i.style.marginLeft=Math.floor(i.width/2)+'px';

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.src='sample.jpg';
i.onload=new Function("this.style.marginLeft=Math.floor(this.width/2)+'px';");
Personal tools