Reputation: 73
What I'm trying to do:
I have an article layout I am making that spans about 700 pixels. At the top of the article is an image. When the image is less than 600 pixels wide, I want the image to float:left;
, but when the image is more than 600 pixels wide, I want the div that it is in, to widen to the full 700 pixels so that it forces the text under neath it.
Example: I have an image that is 640 pixels wide. Unfortunately, the text still wraps and so I get a chunk of words shoved to the right of the image... which is why I want the div that the image is in to span the full width.
I've been trying to get my jQuery to work and I've tried 3 different methods and none work. I think I'm missing something. All it does is make the div span 700 pixels REGARDLESS of the image's width.
<div class="story-img">
<img src="images/sample-article-sm.png" alt="A guy installing Solar Panels" width="350"/><br/>
<span class="caption">Solar panels being installed on a roof.</span>
</div>
jQuery I'm using:
$(document).ready(function() {
var img = $(".story-img > img");
var storydiv = $(".story-img");
var width = img.width();
if (width < 300)
storydiv.addClass("large");
});
The jQuery is working as it should and it is adding the class to the div ".story-img", but it does it regardless of the images width. I thought at first it was because maybe the width isn't specified in the image (this will be dynamically loaded). Why is it not grabbing the width?
Upvotes: 1
Views: 455
Reputation: 121998
Actually you are grabbing the width before the image is added to the dom
So try using a load
event
$('.myImage').load(function(){
alert($(this).width());
alert($(this).height());
//do something here
});
Upvotes: 2