0

JavaScript would probably do it, I have searched but found nothing to do with maxWidth. Only resizing images out of the blue.

What I need is a piece of JavaScript code to resize an image if it's too big(defined in a variable.)

Harry
  • 3
  • 2

2 Answers2

0

Is there some reason why you can't use the max-width CSS property to do what you want, like:

<img src="myImage.png" style="max-width: 600px;">

...or even better:

<style>
    .widthConstrained {
        max-width: 600px; 
    }
</style>

...

<img src="myImage.png" class="widthConstrained">

Edit:

If you must use JavaScript for compatibility reasons, I suggest that you use something like the code specified in this question to check the total image width after it loads, and clamp it down if needed, roughly like:

var img = $("img")[0]; // Get my img elem
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        if (this.width > maxWidth) {
            $(img).width(maxWidth);
        }
    });
Community
  • 1
  • 1
aroth
  • 54,026
  • 20
  • 135
  • 176
  • Apparently, due to Microsofts stupid IE, it is not compatable on non-standards compliant IE. Max-width ofcourse. – Harry Apr 13 '11 at 13:22
  • @Harry - Okay, I updated the answer with a JavaScript version as well. – aroth Apr 13 '11 at 13:31
0

I take it you have a <img /> tag in your webpage.

To shrink images that are too large, simply insert the width and height attribute, along with your image source and a alt, along with a ID.

<head>
    <script type="text/javascript" />
       function pie()
       {
        var pathToImage = "bla/bla/Image.jpg";
        document.GetElementByID(Image1).setAttribute("src",pathToImage);
       }
    </script>
</head>
<body onload=Pie() >
    <img ID="Image1" alt="random Image" width="300px" Height="200px" />
</body>
Eon
  • 3,833
  • 10
  • 46
  • 75
  • the document.GetelementByID() method's syntax will differ between mozilla firefox and IE, because mozilla firefox is not w3c compliant – Eon Apr 13 '11 at 13:28
  • This will also stretch images that are smaller than 300x200, which may not be desired. – aroth Apr 13 '11 at 13:31