tags:

views:

390

answers:

3

On a page I have displayed 100 images, which have the width and height attribute changed. Image id is in a loop.

How do I get the original image size, inside this loop? $(this).appendTo(".prod_image").attr('height',150).attr('width',150).attr('title','').attr('name','').attr('alt','').attr('id','id'+i);

A: 

Could you find your answer here, here, here or here? These Stack Overflow threads all use a combination of jQuery and JavaScript to access/change an image width and height.

slugster
None of them say how to get the "ORGINAL" attrib from an already changed attrib
Jean
That is normally because you can't - try tracking the original value yourself. I thought this would have been obvious.
slugster
+1  A: 

The only way to get the original size is to restore it to its original state. You can do this pretty easily by cloning the image, then removing the height and width attributes to get the real values. You also have to then insert the changed image into the page or else it wont have a calculated height/width. You can do this easily in an offscreen div. Here's an example:

http://jsbin.com/ocoto/edit

The JS:

// Copy the image, and insert it in an offscreen DIV
aimgcopy = $('#myimg').clone();
$('#store').append(aimgcopy);

// Remove the height and width attributes
aimgcopy.removeAttr('height');
aimgcopy.removeAttr('width');

// Now the image copy has its "original" height and width
alert('Height: '+aimgcopy.height()+' Width: '+aimgcopy.width());

The CSS:

  #store {  position: absolute;  left: -5000px; }

The HTML:

  <img id="myimg" src="http://sstatic.net/so/img/logo.png" width="300" height="120"/>
  <div id="store"></div>
Erik
A: 

I had to perform a similar task with a jQuery plugin I created. It keeps state for an inputs text value, but the principle could easily be used for your width and height.

I would create a custom object that stores the original object's ID, Width and Height. That object is then put into an array. When required to restore the value simply loop the array of custom objects to match ID and bingo, an object with the original width and height.

You can check out my plugin's code at www.wduffy.co.uk/jLabel to see how I implemented this. Depending on how many images you are changing the array could become a little on the heavy side though.

An example might look like

var states = new Array();

function state($obj) {

    // Public Method: equals
    this.equals = function($obj) {
        return $obj.attr('id') == this.id;
    };

    // Public Properties
    this.id = $obj.attr('id');
    this.width = $obj.attr('width');
    this.height = $obj.attr('height');

};

function getState($obj) {
    var state; 

    $.each(states, function() {
        if (this.equals($obj)) {
            state = this;
            return false; // Stop the jQuery loop running
        };
    });

    return state;
};
WDuffy