I am working on javascript tool for a client site at the moment, basically the users selects a colour from a drop down list, and the client then wants that image for that colour to be displayed.
There are a view problems however, the system the client uses has no way of adding id’s or classes to the image, so I cant just do a simple,
if (select value = a class)
{
showImage
}
What I have had to do so far, is add the images colour to the image’s alt text, so a image title might typically looks like this:
A sock, Green
So far I have the following code:
$('.information select#colours').change(function(){
var colour = $(this).val();
});
On my page there can be any number of product images, and their markup will look like this,
<div class="carousel js" tabindex="0">
<ul class="alternative_images" style="position: absolute; top: 0px; width: 60px; height: 276px;">
<li>
<a href="/uploaded/thumbnails/db_file_img_4_254x347.jpg">
<img alt="Ben Fogle Sock, Grey" src="/uploaded/thumbnails/db_file_img_9_58x79.jpg">
</a>
</li>
<li>
<a href="/uploaded/thumbnails/db_file_img_4_254x347.jpg">
<img alt="Ben Fogle Sock, Green" src="/uploaded/thumbnails/db_file_img_7_58x79.jpg">
</a>
</li>
<li>
<a href="/uploaded/thumbnails/db_file_img_4_254x347.jpg">
<img alt="Ben Fogle Sock, Red" src="/uploaded/thumbnails/db_file_img_5_58x79.jpg">
</a>
</li>
</ul>
My question is
1) How can I collate all the colours of the images that are found in the images alt after a comma?
2) How can I then search through those colours to pull back the correct image?
Is there a better way of doing this?
Several people have added working answers, but I’m thinking if you have enough images to filter by color you may be interested in performance, too, which means that selecting all of the image elements and parsing their alt text every time the filter option is changed isn’t the best solution.
An alternative is to do this once, extracting the colors only on pageload and adding them as a CSS class on the images. Since modern browsers optimize class lookups with
querySelectorAll(and jQuery uses this optimization whenever possible) you can then do a plain old class select and expect good performance:(If performance is still an issue another option is to build a hash table (using a JavaScript object) e.g.
var els = { "Red" : [ <img src...>, <img...>, ... ], "Blue" : [ <img...>, ...] }for very fast lookups e.g.els[ "Blue" ].)