Reputation: 1223
I have a simple image gallery with different image size. I'm going to get the width of the current image and assign it to it's parent div using jquery but I can't seem to get it working. Thanks for any help.
var imgWidth = $("#image").width();
$("#gallery").css({ width : imgWidth });
Sample HTML:
<div id="gallery">
<img src="123.jpg" id="image" />
</div>
Upvotes: 1
Views: 1234
Reputation: 10645
You're going to kick yourself for this......
Your jsfiddle was set to use mootools not jQuery.
Here's a working update link
Upvotes: 1
Reputation: 6866
You need to specify "px"
Like so:
var imgWidth = $("#image").width();
$("#gallery").css({ width : imgWidth+"px" });
Assuming the image is loaded when your javascript is executing this should work. If not you'll have to place this code inside a $(window).load(function(){});
as Edgar says or possibly even a $("#image").load(function(){});
.
Upvotes: 1
Reputation: 18354
Your code seems ok. But you may be trying when the image hasn't been loaded yet. $(document).ready
wouldn't help in this case.
Try this:
$(window).load(function(){
var imgWidth = $("#image").width();
$("#gallery").width(imgWidth);
});
Hope this helps. Cheers
Upvotes: 3