PDA

View Full Version : Need help fixing image dimensions script..



ShadowIce
06-17-2009, 10:54 PM
Hi all, I've been researching image data, and i've come to a bump in the road.

I get an undefined value when i try to scale my image and times it by a # like 2.

Here's the code:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function getwidth(){
var wth;
for(i = 0; i < window.document.images.length; i++)
{
wth = window.document.images[i].width;
}
alert(wth);
return wth;
}
function getheight(){
for(i = 0; i < window.document.images.length; i++)
{
hgt = window.document.images[i].height;
}
return hgt;
}
</script>
</head>
<img width="getwidth()*2" height="getheight()*2" src="c:/xampp/htdocs/imageposeidon/images/indian.gif"/></img>
</body>
</html>

ANY help is GREATLY appreciated, any criticism is GREATLY ignored! ;)

Thanks! :)

~SI~

jscheuer1
06-18-2009, 05:01 AM
The simple answer is, you can't do this:



<img width="getwidth()*2" height="getheight()*2" src="c:/xampp/htdocs/imageposeidon/images/indian.gif"/></img>

Aside from the fact that it would be better to address the specific image in your other script code rather than loop through all images in the document (which actually should work if there is only one, but is wasteful), you cannot just slap a function call into an attribute that isn't itself an event (like mouseover, click, etc.).

You could do something like (untested and not necessarily the best way):


<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function dubDims(){
var i = document.images[0], s = i.style, w, h;
w = i.width * 2;
h = i.height * 2;
s.width = w + 'px';
s.height = h + 'px';
};
onload = function(){
document.images[0].onload = dubDims;
document.images[0].src = 'c:/xampp/htdocs/imageposeidon/images/indian.gif';
};
</script>
</head>
<body>
<img>
</body>
</html>

Added Later:

My above method will work in most browsers. However, it is not valid HTML and has problems in the KHTML based browsers like Chrome and Safari.

Still not the best method probably, but it validates, will loop through all images, and works in more browsers:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
onload = function(){
function dubDims(){
var i = this, s = i.style, w, h;
w = i.width * 2;
h = i.height * 2;
s.width = w + 'px';
s.height = h + 'px';
};
for (var s, i = document.images.length - 1; i > -1; --i){
s = document.images[i].src;
document.images[i].src = '';
document.images[i].onload = dubDims;
document.images[i].src = s;
}
};
</script>
</head>
<body>
<div>
<img src="images/contactbutton2_o.png" alt="">
</div>
</body>
</html>