Reputation:
Maybe this is a very stupid question, but not stupid enough for me since I can't seem to figure this out (even with Google).
I have this jquery:
$.each(items, function (key, t) {
$("#list").append(
$("<li />")
.append($("<img />")
.attr("src", "path/to/" + t.Thumbnail)
.addClass("thumb"))
.append($("<span />")
.html("<b>" + t.Title + "</b><br />" + t.Description)));
});
After this I loop through the thumbs to do some styling (with size and ratio, not relevant here)
$(".thumb").each(function () {
console.log($(this));
});
In the console I see this:
[img.thumb, context: img.thumb, jquery: "1.9.0", constructor: function, init: function,
selector: ""…]
0: img.thumb
context: img.thumb
length: 1
__proto__: Object[0]
What is this context? With $(this).width() it gives an error or 0. When I have an image that is already on the page it just...works?!
So, the problem is: Why doesn't this work and why does it work on other pages?
Thanks in advance
EDIT: Added an example to Fiddle: http://jsfiddle.net/nN9ce/
Upvotes: 1
Views: 123
Reputation: 5221
Try this instead:
$(".thumb").each(function (idx, thumb) {
console.log($(thumb));
console.log($(thumb).width());
});
Here is updated fiddle:
Upvotes: -1
Reputation: 1023
You haven't set the width and height attributes on the images. Try making this change:
.attr("src", "http://www.logoquizantwoorden.nl/wp-content/uploads/2012/06/Logo-Quiz-uitleg.png")
.attr("height", "128")
.attr("width", "128")
.addClass("thumb")
Fiddle: http://jsfiddle.net/sBSnS/
Upvotes: 0
Reputation: 9329
.width()
gets the size of the element, and not the image itself. When the script runs, although the images have been added to the dom, they aren't loaded yet so the elements have a width of 0 (even if the images you are about to load into those elements are of width 128).
You need to run a callback after the images are loaded.
Upvotes: 3
Reputation: 572
Not sure about the method problem but you can use the property
width
So, you'd have this.
$(".thumb").each(function () {
console.log(this.width);
});
Upvotes: -1