Is it possible to set an elements width like this:
<img id="backgroundImg" src="images/background.png" alt="" width="javascript:getScreenSize()['width']+px" height="1100px"/>
Where getScreenSize() is a javascript function.
function getScreenSize()
{
var res = {"width": 630, "height": 460};
if (document.body)
{
if (document.body.offsetWidth) res["width"] = document.body.offsetWidth;
if (document.body.offsetHeight) res["height"] = document.body.offsetHeight;
}
if (window.innerWidth) res["width"] = window.innerWidth;
if (window.innerHeight) res["height"] = window.innerHeight;
alert( res['width'] );
return res;
}
Or do I have to change the img’s width inside a javascript function?
function changeImgWidth( img )
{
img.offsetRight = getScreenWidth()['width'] + "px";
}
You can’t do it with that syntax, no. You could use
document.writeto do it, but I suspect you’d be better off doing it after the DOM loads, because I think yourgetScreenSizefunction may not report correct results until then (but it may, you’ll have to test).To do it with
document.write:To do it once the DOM is loaded, put this at the very end of your page, just before the closing
</body>tag:In both of those examples, I’ve stuck with the
widthattribute (note that you don’t use a units suffix — “px” — with thewidthattribute). But you might consider using the CSSwidthproperty instead (which you would use the suffix with).Stepping back, though, rather than relying on JavaScript to set the width, I’d recommend trying to do it with CSS. You can make the image 100% of the width of its container by using
style='width: 100%'within the tag or:…in a stylesheet.