Chosen Image in dropdown
by ian_smithz
HTML
<link rel="stylesheet" href="http://lysik.pl/public/chosen.css">
<script src="http://lysik.pl/public/chosen.jquery.js"></script>
<select class="my-select" id="my-select" style="width:350px;" tabindex="2">
<option data-img-src="http://i.stack.imgur.com/8lgcm.jpg">Project A</option>
<option data-img-src="https://www.gravatar.com/avatar/ecb87e13fc7cc038a774e2785f217f8a?s=24&d=identicon&r=PG">Project B</option>
</select>
<br>
<a href="https://github.com/djgrant/chosen-image">Chosen Image</a>
CSS
/* DG - 29/11/12 - Align single item with results. General UI Imrpovement */
.chzn-container-single .chzn-single {
padding: 0 0 0 10px;
}
/* DG - 03/12/12 -chosenImage - position, size and indent text */
.chznImage-container .chzn-results li,
.chznImage-container .chzn-single span {
background-position: 6px 45%;
background-size: auto 12px;
padding-left: 23px;
}
.chznImage-container .chzn-single span {
background-position: 0px 45%;
padding-left: 17px;
}
JavaScript
(function($) {
$.fn.chosenImage = function(options) {
console.log('Image chsn');
return this.each(function() {
var $select = $(this),
imgMap = {};
// 1. Retrieve img-src from data attribute and build object of image sources for each list item
$select.find('option').filter(function(){
return $(this).text();
}).each(function(i) {
var imgSrc = $(this).attr('data-img-src');
imgMap[i] = imgSrc;
});
// 2. Execute chosen plugin
$select.chosen(options);
// 2.1 update (or create) div.chzn-container id
/*var chzn_id = $select.attr('id').length ? $select.attr('id').replace(/[^\w]/g, '_') : this.generate_field_id();*/
var chzn_id = $select.attr('id');
chzn_id += "_chzn";
console.log('before class addition');
var chzn = '#' + chzn_id,
$chzn = $(chzn).addClass('chznImage-container');
console.log(chzn);
console.log($(chzn).length);
console.log($("#my-select").length);
// 3. Style lis with image sources
$chzn.find('.chzn-results li').each(function(i) {
$(this).css(cssObj(imgMap[i]));
});
// 4. Change image on chosen selected element when form changes
$select.change(function() {
var imgSrc = ($select.find('option:selected').attr('data-img-src'))
? $select.find('option:selected').attr('data-img-src') : '';
$chzn.find('.chzn-single span').css(cssObj(imgSrc));
});
$select.trigger('change');
// Utilties
function cssObj(imgSrc) {
if(imgSrc) {
return {
'background-image': 'url(' + imgSrc + ')',
...