3

i would like to output the width and height of an image before appending that to the browser. Of course, i get 0 for the width and 0 for the height, cause the image is not appended to the DOM yet.

I have uploaded my code to http://jsfiddle.net/BF5En/4/

How can i take the right values before appending the image to the DOM??

Thanks, in advance!

programmer
  • 193
  • 1
  • 4
  • 11

2 Answers2

3

You seem to have very interesting questions. This is my humble answer:

$(document).ready(function() {
    $(".Photos a").click(function () {
        var href_attribute = $(this).attr('href');
        var new_item = $('<img src="' + href_attribute + '" />')
            .hide()
            .load(function () {
                alert('Img was loaded! Width: ' + this.width + ' and height: ' + this.height);
            })
            .fadeIn(2000)
            .appendTo('.AppendingDiv');
        return false;
    });
});

Live example: http://jsfiddle.net/hobobne/BF5En/10/

You see, you must make sure that the image is preloaded, for that we use .load(). Otherwise you will get 0. That's actually good, because it means that the script works, just everything is so fast, that it can get the dimensions. .load() makes sure that the image is first loaded and only then receive the dimensions.

For whatever purposes you wanted to use the dimensions, I recommend doing that inside the .load() as well. Because you probably will have multiple .Photos a anyways.

Also, as you might have noticed your .fadeIn(2000) was not working. That's because, your item got appended before you called it. As you can see, I fixed it for you :)

NB! Sorry, I renamed some of the variables (made stuff more logic in my head.)

Kalle H. Väravas
  • 3,579
  • 4
  • 30
  • 47
0
var MyitemWidth = item.css('width');
var MyitemHeight = item.css('height');

see this answer Getting auto size of IMG before adding it to DOM (Using JQuery)

DOM elements have dimensions only when added to a parent, as dimension is determined by the 
rendering engine. To go around this issue, have a <div> container absolutely positioned off 
screen, add the image to it first, get the dimension, then add the image at it's final destination.
Community
  • 1
  • 1
Rafay
  • 30,950
  • 5
  • 68
  • 101
  • Thanks for the anwser but i still get zeros for both height and width because the image is not appended to the browser yet – programmer Aug 20 '11 at 11:15
  • Thanks for the link, as i understood they propose using a "container absolutely positioned off screen". Is that the only solution or the best solution for the problem??I'm a bit confused with that...If i use the .load() function,am i going to have the desirable result??Is my layout going to be ruined with that absolute positioned element?? – programmer Aug 20 '11 at 11:39
  • this may help http://stackoverflow.com/questions/1782566/determine-whether-element-has-fixed-or-percentage-width-using-javascript/1783565#1783565 – Rafay Aug 20 '11 at 11:42