0

I have some dynamically generated content on which I need to use color thief to find the dominant colour. Here's the final dynamic output:

<div class="image_product">
    <img style="display:none;" src="image1.jpg">
    <img style="display:none;" src="image2.jpg">
</div>
<div class="image_product">
    <img style="display:none;" src="image3.jpg">
    <img style="display:none;" src="image4.jpg">
</div>

And here's the script I'm trying:

var colorThief = new ColorThief();
$('div.image_product').each(function() {
    $(this).find('img').each(function() {
        var color = colorThief.getColor(this[0]);
        console.log(color);
    });
});

I've managed to get it working in other areas where I know there is only one image, with the following code:

var colorThief = new ColorThief();
$('div.basket_item_image').each(function() {
    if($(this).children("img").length > 0)
    {
        var img = $(this).find('img');
        var color = colorThief.getColor(img[0]);
        console.log(color);
    }
});

And I know you have to add the [0] when using it with JQuery to make it access the DOM correctly, but I can't see how my middle code isn't working. Any ideas?

Helen Danger Burns
  • 421
  • 2
  • 9
  • 28

1 Answers1

0

You don't need the this[0]. Inside each(), this is the current HTML element being iterated and not a jQuery object, per the docs:

More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

Therefore, just use this to access the current element (the current <img />) whilst inside each().

var colorThief = new ColorThief();
$('div.image_product').each(function() {
    $(this).find('img').each(function() {
        var color = colorThief.getColor(this);
        console.log(color);
    });
});
Matt
  • 74,352
  • 26
  • 153
  • 180
  • 1
    @HelenDangerBurns; I'm afraid you don't. When you call `each()` on a jQuery object, jQuery invokes the callback you pass for each element in the jQuery object. Inside that callback, `this` is the raw DOM element, not a jQuery object. If it *was* a jQuery object, you **would** have to use `this[0]`, but it's not, so you don't. – Matt Jun 18 '14 at 15:28
  • OK, but `this` on it's own doesn't work. I see why you shouldn't need `[0]`, but then why doesn't it work?! So confused! – Helen Danger Burns Jun 18 '14 at 15:30
  • @HelenDangerBurns: Can you come up with a jsfiddle which demonstrates the problem? I can't even get colorThief to work for me... the library throws an exception on line 131. – Matt Jun 18 '14 at 15:39
  • I'm afraid not... I can't get the cross domain images to work. I think it has to be local. – Helen Danger Burns Jun 18 '14 at 16:29