Tag-Archive for ◊ selectbox ◊

Custom select box upgrade
Thursday, September 30th, 2010 | Author:

I’ve made a little improvement on my custom select box mootools class.

Custom selectbox now:

  1. applies the selected element as active and
  2. fires the change event of it’s select tag.

Use the selected property on the option tag:

<option value="40" selected="selected">fourty</option>

Define onchange event through property:

<select onchange="alert('Ninja!');">

Or add event change through mootools:

$('sel2').addEvent('change', function(){
	if(this.value == 70) alert('You hit 70!');
});

See demo here.

We all know that the HTML <select><option> element is almost impossible to design in you own way. The pure HTML selectbox is ugly and web designers allways want to style them in their own way. The whole process can be painful for web developers because you have to create a fake dropdown list with some stylable HTML elements and apply some javascript on them in order to recreate the same or at least similar behaviour.

I created a MooTools class which is:
  • Custom selectbox created from <select> and <option> elements
  • Fully CSS and HTML customizable
  • Allways positioned above all other elements
  • With full keyboard interaction
  • XHTML 1.0 Strict compliant and validated
  • Tested in IE6, IE7, IE8, Firefox 3.6, Opera 10.10, Chrome 4, Safari 4, Nokia N97
Usage:

Put a standard <select></select> element inside your form and add a class=”custom” to it. Put in some <option></option> elements  as usual.

<select name="first" class="custom">
    <option value="1">first element</option>
    <option value="2">second element</option>
    <option value="3">third element</option>
    <option value="4">fourth element</option>
</select>

Inside <head> element you shoud put some javascript:

window.addEvent('domready',function(){
	$$('select.custom').each(function(el){
		new cSelectBox(el);
	});
});

It ensures that all your <select> elements are replaced with:

<div class="cDropdown first">
    <a href="#" class="cSelect"></a>
    <ul class="cOptions">
        <li><a href="#" rel="1" class="cActive">first element</a></li>
        <li><a href="#" rel="2">second element</a></li>
        <li><a href="#" rel="3">third element</a></li>
        <li><a href="#" rel="4">fourth element</a></li>
    </ul>
</div>

Elements <div>, <a> and <ul> are easy to customize through CSS and they behave as real selectbox. The attribute name from <select> element is attached to <div>’s class in order to customize each selectbox in it’s own way.

And that’s it. See demo here.