7

SOLVED: Syntax-Error

The following code works:

var image = {width:0,height:0};
var imageObject = new Image();
function getImageSize(id) {
    imageObject.src = id.attr("src");
    image.width = imageObject.width;
    image.height = imageObject.height;
}

Original Question

I want to get the original width and height of an image and tried different code to achieve it. My function triggers on click event and all images are resized to 400x300.

I tried to resize the Image to its original size by using auto:

var image = {width:0,heigth:0};
function getImageSize(id) {
    id.css({
        'width': 'auto',
        'heigth': 'auto'
    });
    image.width = id.attr('width');
    image.heigth = id.attr('heigth');
}

Attaching auto didn't change the size of the image.

alert(id.attr('width')); always returns 'undefined'. so it doesn't work

var image = {width:0,heigth:0};
var imageObject = new Image();
function getImageSize(id) {
    imageObject.src = id.attr("src");
    image.width = imageObject.width;
    image.heigth = imageObject.heigth;
}

alert(image.width); works perfectly.

alert(image.heigth); returns undefined.

Using imageObject.naturalWidth works as the one above - the width is given correctly but the heigth is undefined.

I read that you have to append the new image object, but when I use imageObject.appendTo('body'); I can't even click the image.

Thanks for any suggestions.

CadanoX
  • 79
  • 2
  • 5

1 Answers1

2

This is a simple contained example of replacing an image with one that has its original sizes after having been altered.

<img src="http://www.finesttreeserviceaz.com/wp-content/uploads/2012/02/tree2.gif" id="bar" />
<script type="text/javascript">
    var myImg = document.getElementById("bar");
    myImg.setAttribute("style", "width:400px;height:300px;");
    function resetBar() {
        var newImg = new Image();
        var oldImage = document.getElementById("bar");
        newImg.src = oldImage.src;
        oldImage.parentNode.replaceChild(newImg, oldImage);
    }
    setTimeout("resetBar();", 2000);
</script>

An alternative would be to remove the style that was applied:

myImg.removeAttribute("style");
Travis J
  • 81,153
  • 41
  • 202
  • 273