0

I am probably being very very stupid. But i cant get this to work for my life. I am trying to set the imgWidth to the same width as the image width of the file (pic_real_width).

function calculate() {
    var pic_real_width, pic_real_height;
    $("<img/>").attr("src", $("#pp_photo_popUp")[0].src).load(function() {
        pic_real_width = this.width;   // Note: $(this).width() will not
        pic_real_height = this.height; // work for in memory images.
    });
    var imgWidth = 
}

All in all I am trying to make a function to get the real dimensions of a file on the hard disk.

surfmuggle
  • 5,527
  • 7
  • 48
  • 77

1 Answers1

4

Bind the load event First, and then do all processing that needs the image to be loaded inside of the load event.

function calculate(callback) {
    $("<img/>").load(function() {
        var pic_real_width = this.width;   // Note: $(this).width() will not
        var pic_real_height = this.height; // work for in memory images.
        callback(pic_real_width,pic_real_height);
    }).attr("src", $("#pp_photo_popUp")[0].src);
}

calculate(function(width,height) {
    console.log(width,height);
});

If you set the src first, some versions of IE will immediately trigger the load event synchronously, thus triggering it before you have even bound to it. That's why i swapped the order. Additionally, I added the callback parameter because I assume later in the function you were going to return the width/height, which won't work due to the asynchronous nature of load events.

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • Are you sure it's only "some versions of IE"? I think it's all browsers...if the image is cached, the `load` event fires immediately when setting the `src`. I've never really had to test this (especially in all browsers) though – Ian Jul 17 '13 at 19:21
  • It may be all versions of IE, but some browsers do actually trigger the event asynchronously when it is cached, meaning binding the event after setting the src will work in those browsers even on cached images. I'm not sure about current versions of the browsers, all the testing i did on this was ~ a year ago and IE was the only browser that triggered it synchronously. – Kevin B Jul 17 '13 at 19:24
  • @KevinB kinda saved my day, thanks, I should have thought of this being an asynchronous function. How process intensive is this though? I mean if I were to call this every time when a user switches to the next photo, would that be fine? – Pash Shocky Jul 17 '13 at 22:10