FBwall
FBwall

Reputation: 1653

Grabbing image height and setting it to its container jquery

I have a div for my posts which may contain images with different sizes and i need to set their container's width individually. How do i do that?

<div class="panel">
<img id="screeny" src="http://localhost/531q3n.jpg"/>
</div>

Here's my current try but something's wrong:

var img = document.getElementById('screeny'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
$('.panel').css("width",width+"px");

Upvotes: 0

Views: 1137

Answers (2)

adeneo
adeneo

Reputation: 318342

The image must be loaded before you have access to it's size, like so:

var img = $('#screeny'); 
img.load(function() {
    var width = img.width();
    var height = img.height();
    $('.panel').css("width", width);
});

EDIT: for more than one image, if they are all in a div with the class 'panel':

$("img", ".panel").each(function() {
    $(this).load(function() {
        var width = $(this).width();
        var height = $(this).height();
        $(this).parent().css("width", width);
    });
});

Upvotes: 1

John Strickler
John Strickler

Reputation: 25421

$('#screeny').load(function() {
  $(this).parent().css('width', $(this).width());
});

Attach a handler that will execute when the image has finished loading. This will set the parent (container) to the width of the image.

Upvotes: 0

Related Questions