tags:

views:

488

answers:

3

I am creating a photo gallery using jquery. I am taking and resizing the images on load to create thumbnails. I want to get the original value of the image's size so that later on I can take it back to its original size. Anyone know how to do this? I have the following code:

    obj.find("img").each(function(){
}); 

This loops through all the images within the container div. I then tried to do:

$(this).width(); //didnt work
this.width; //didnt work

any ideas?

+1  A: 

I asked the same question recently and got a good answer: A new image element is created but not attached to the DOM. Its height and width are the original dimensions of the image.

Edit: I edited the answer to my question now as promised in the comments. Detection of the image size is now bound to the onload event of the image to guarantee reliable results.

Pekka
A: 

If an element is hidden you can't get its size, if you want to get its width or height before showing it, you need to give a negative left offset like

#your_image {left:-1000%;}

, only then

$(this).width()

will return you the correct result.

Hope it helps, Sinan.

Sinan Y.
A: 

The problem with using jQuery to get image size is that usually we use $().ready(function()); to exec our javascript, but at that point the page load, the image isn't loaded yet, so you need to wait for that to happen first. Once you're sure the image is loaded, and the image is visible, you can use $.width() and $.height() as normal.

One thing you might try as well if you're using a scripted language to generate your image sizes is to put the width and height attributes after reading the file and getting the size that way. Since you're making a gallery, you might consider resizing your images on the backend with imagemagick of gd for php. There is plenty of documentation online for those tools, so I won't get into it here.

Aaron