50/50 select widget
50/50 select widget
HTML
<p>Simple</p>
<select class="customSelect">
<option>Mercury</option>
<option>Saturn</option>
<option>Earth</option>
<option>Venus</option>
</select>
<p>Default selection</p>
<select class="customSelect">
<option>Mercury</option>
<option>Saturn</option>
<option selected="selected">Earth</option>
<option>Venus</option>
</select>
<p>Limit to 4 chars + elipsis</p>
<select class="customSelect" data-limit="4">
<option>Mercury</option>
<option>Saturn</option>
<option selected="selected">Earth</option>
<option>Venus</option>
</select>
<p>Dynamically added options</p>
<select id="add-options" class="customSelect">
<option>Mercury</option>
<option>Saturn</option>
<option selected="selected">Earth</option>
<option>Venus</option>
</select>
CSS
.swCont {
position: relative;
}
.swCont span.swLabel {
display: block;
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0, rgb(16,117,180)),
color-stop(0.62, rgb(51,162,241))
);
background-image: -moz-linear-gradient(
center bottom,
rgb(16,117,180) 0%,
rgb(51,162,241) 62%
); border-radius: 3px;
padding: 4px 6px;
border: solid 1px #1C1C1C;
box-shadow: 0 1px 0 #5A5D63;
width: 200px;
}
.swCont select.customSelect {
width: 200px;
font-size: 1.4em;
}
body {
background: #40434A;
color: #fff;
font-family: Helvetica;
font-size: 13px;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.6);
font-weight: bold;
}
p {
margin: 15px 0 3px;
}
JavaScript
var Widget = {};
Widget.Select = new Class({
Implements: [Options, Events],
options: {
label: {
'tag': 'span',
'className': 'swLabel'
},
cont: {
'tag': 'div',
'className': 'swCont'
},
labelLimit: 14
},
initialize: function(widgets, options) {
this.widgets = widgets;
this.setOptions(options);
this.label = [];
this.checkWidgets();
},
checkWidgets: function() {
this.widgets.each(this.prepare, this);
},
prepare: function(widget, index) {
widget.set('styles', {
opacity: 0.001,
position: 'absolute',
top: 0,
left: 0,
display: 'block'
});
this.label[index] = Element(this.options.label.tag, {
'text': widget.getSelected().get('text'),
'class': this.options.label.className
});
Element(this.options.cont.tag, {
'class': this.options.cont.className
}).wraps(widget).adopt(this.label[index]);
this.attachListener(widget, index);
widget.fireEvent('change');
},
attachListener: function(widget, index) {
widget.addEvents({
change: function() {
var limitMode = widget.get('data-limit');
var newLabel = widget.getSelected().pop().get('text');
newLabel = (newLabel.length > (limitMode || this.options.labelLimit) ? newLabel.substring(0, (limitMode || this.options.labelLimit)) + ' …' : newLabel);
this.label[index].set('text', newLabel);
}.bind(this)
});
},
update: function(widget, newOptions) {
newOptions.each(function(newOption) {
widget.getElements('option').each(function(option) {
option.selected = false;
});
var newOptionEl = Element('option', {
text: newOption.text,
...