Why can not I change the width of an image using this feature?

advertisements

I am trying to change the width of the image to 200px (fixed size) only if the image width is greater than 200px, else i want to leave its original width.

now below code works:

<img src="../images/browse-files.png"  style="width:200px" onload="var img = new Image(); img.src = this.src; if(img.width <= 680){ var imgW= '680' + 'px' ; this.style.width =imgW;} "/>

But below code doesn't:

<script type="text/javascript">
resize(){
var img = new Image();
img.src = this.src;
    if(img.width <= 680){
        var imgW= '680' + 'px' ;
        this.style.width = imgW;
    }
return this.style.width;
}
</script>

<img src="../images/browse-files.png"  style="width:200px" onload="return resize() "/>

I would like to know what i am doing wrong with the last method. I prefer the last methose cos i want to include all the JavaScript functions on one .js page.

Thanks a lot.


You can't put the onload event onto an image element like that, it has to go on the instance of Image. Check out this (or reference code below) to get a good start. I first created an instance of Image so that I could detect when it loads. Then, onload of the image, check and see if the size is greater than 200. If it is, get the original image element, not the instance of Image, and resize it.

var image = document.getElementById("image");

var img = new Image();
    img.src = image.src;

img.onload = function(){
    if (img.width > 200) {
        image.style.width = "200px";
    }
};