1

I'm totaly confused with this piece of code. When I just load the page imgWidth1 and imgHeight1 are both equal to "0" But when I resize my window, the code works and imgWidth1 and imgHeight1 have the same value as the image dimension.

All help is welcome, thanks.

var imgWidth1 = $("#image-hover-0").outerWidth();
var imgHeight1 = $("#image-hover-0").outerHeight();

$("#hover-img-0").css("width", imgWidth1 + "px");
$("#hover-img-0").css("height", imgHeight1 + "px");
$("#hover-img-0").css("line-height", imgHeight1 + "px");

$(window).resize(function() {

    var imgWidth = $("#image-hover-0").outerWidth();
    var imgHeight = $("#image-hover-0").outerHeight();

    $("#hover-img-0").css("width", imgWidth + "px");
    $("#hover-img-0").css("height", imgHeight + "px");
    $("#hover-img-0").css("line-height", imgHeight + "px");

});
Simon
  • 179
  • 2
  • 3
  • 12
  • This can happen if the image isn't loaded fully. Are you sure it is fully loaded when you're getting 0? – cfly24 Aug 21 '15 at 12:54
  • because the image is not loaded yet. see: http://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript – Hacketo Aug 21 '15 at 12:54
  • There's the possibility this is executed too early and the image is not available when calling the properties. You could try to wrap this in a window `load` event handler. – spenibus Aug 21 '15 at 12:54

2 Answers2

4

This is most likely due to the fact that your code is not nested inside a $(window).load() function call. Modify your code to the following:

$(window).load(function(){
    var imgWidth1 = $("#image-hover-0").outerWidth();
    var imgHeight1 = $("#image-hover-0").outerHeight();

    $("#hover-img-0").css("width", imgWidth1 + "px");
    $("#hover-img-0").css("height", imgHeight1 + "px");
    $("#hover-img-0").css("line-height", imgHeight1 + "px");

    $(window).resize(function() {

        var imgWidth = $("#image-hover-0").outerWidth();
        var imgHeight = $("#image-hover-0").outerHeight();

        $("#hover-img-0").css("width", imgWidth + "px");
        $("#hover-img-0").css("height", imgHeight + "px");
        $("#hover-img-0").css("line-height", imgHeight + "px");

    });
});
spenibus
  • 4,339
  • 11
  • 26
  • 35
jonny
  • 3,022
  • 1
  • 17
  • 30
0

I faced this problem before. But still the question is, do you want the real size? or the size showed on the screen ?

For the first, you should wait the image to be loaded after you can get the real size :

yourImage.addEventListener('onload',  
  function() {
    console.log("pic's width : ", this.naturalWidth);
    console.log("pic's height : ", this.naturalHeight);
});

For the second, you must encupsle it within a div and get its size.

I hope that my answer may helps you.

Waver
  • 1
  • 4