Simon
Simon

Reputation: 199

Can't get img width and height jQuery

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");

});

Upvotes: 1

Views: 1157

Answers (2)

Waver
Waver

Reputation: 1

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.

Upvotes: 0

jonny
jonny

Reputation: 3098

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");

    });
});

Upvotes: 4

Related Questions