There are several pictures of different colors (red, green, yellow), how to use jquery to sort by color, that is, you click on red, all photos are displayed with red. jquery just learning, you can throw off manuals or read something, thanks.
1 answer
- Tag each image with tags of corresponding colors (for example, adding the data-colors attribute to the corresponding html elements)
- Go around all the elements and hide (delete) those in the data-color of which there is no selected color.
var $pictures = $('.picture'); var selectedColor = 'red'; $pictures.each(function() { var colors = $(this).data('colors'); if (colors.indexOf(selectedColor) === -1) { $(this).hide(); } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="picture" data-colors="["red","pink"]"> 1 ... </div> <div class="picture" data-colors="["green","blue"]"> 2 ... </div> <div class="picture" data-colors="["red"]"> 3 ... </div> Data about what color picture you can get from anywhere, or even calculate at run time. The calculation of the main color of the image is quite an interesting task, although you can use some ready-made solution (for example, dominant-color ). Having received the main shade, you can "round off" it to one or several basic colors by which you will filter.
|