2

I have an image that changes when the user clicks a different thumbnail.

How do I make it reliably get the dimensions of the image that is about to be loaded?

Currently I have:

$('#mainImg').animate({opacity: 0.01}, 500, function() {
    $('#mainImg').attr('src', '/cakes/' + file);
    setTimeout(function() {
        center('#mainImg');
        $('#mainImg').animate({opacity: 1.00}, 500);
    }, 100)

})

Which is a work around that is a little more reliable than what I previously had:

$('#mainImg').fadeOut('fast', function(){
    $('#mainImg').attr('src', '/cakes/'+file);
    center('#mainImg');
    $('#mainImg').fadeIn('fast');
})

Function center is for now just:

function center(imageElement)
{
    var ph = $(imageElement).parent().height();
    var pw = $(imageElement).parent().width();

    var ih = $(imageElement).height();
    var iw = $(imageElement).width();
    alert(iw)
}
Krish R
  • 22,583
  • 7
  • 50
  • 59
imperium2335
  • 23,402
  • 38
  • 111
  • 190

3 Answers3

1

You should preload image first to have reliable dimensions. Try something like this:

$('#mainImg').animate({opacity: 0.01}, 500, function() {
    var $this = $(this),
        src = '/cakes/' + file;
    preloadImage(src, function() {
        $this.attr('src', src);
        center($this);
        $this.animate({opacity: 1.00}, 500);
    });
});

preloadImage(src, callback) {
    var img = new Image();
    img.onload = callback;
    img.src = src;
}

Also modify center function to use already available cached variable:

function center($imageElement) {
    var ih = $imageElement[0].height;
    var iw = $imageElement[0].width;
    alert(iw)
}
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • @dsfq I got it to work thanks :) Just need to figure out how to get the parent element height of the main image because now it is saying Object # has no method 'parent' – imperium2335 Feb 01 '14 at 08:42
  • Wrap what ever you use in `$()`: `$(whatever).parent()`. – dfsq Feb 01 '14 at 09:17
0

I think you'll have to preload that image, something like this:

    var image = new Image();
    image.src = "https://www.google.nl/images/srpr/logo11w.png";
    image.onload = function () {
        // Do whatever you want with this.width and this.height overhere.
        console.log(this.width);
        console.log(this.height);
    }
Ambidex
  • 755
  • 1
  • 5
  • 27
0

Simular to the already posted answers but with a fallback for the browsers that do not support the load event for images properly:

$('#mainImg').animate({opacity: 0.01}, 500, function() {
    // run the load event only once
    $('#mainImg').one('load', function() {
        // do whatever you want to do if image is loaded...
        console.log(this.width);
        console.log(this.height);
    })
    .attr('src', '/cakes/' + file);
    .each(function() {
      //Cache fix for browsers that don't trigger .load()
      if(this.complete) $(this).trigger('load');
    });
})
axel.michel
  • 5,764
  • 1
  • 15
  • 25