magnobiet
2/13/2014 - 3:27 PM

jQuery Custom Select (http://codepen.io/magnobiet/pen/BFlsn)

/*!
 *
 * jQuery Custom Select v0.1.4
 *
 * Made by Magno Biét
 * Under MIT License
 *
 */

;(function($, window, document, undefined) {

	var pluginName = 'customSelect',
		defaults = {
			classWrap: 'custom-select-wrap',
			classFocus: 'focus',
			classValue: 'value',
			classDisabled: 'disabled',
			paddingRight: 30
		};

	function Plugin(element, options) {
		this.element = element;
		this.settings = $.extend({}, defaults, options);
		this._defaults = defaults;
		this._name = pluginName;
		this.init();
	}

	Plugin.prototype = {

		init: function() {

			this.selectReplace(this.element, this.settings);

		},

		selectReplace: function(element, settings) {

			var self = $(element),
				classFocus = settings.classFocus,
				initialValue = self.find('option:selected').text();

			self.addClass('original');
			self.wrap('<div class="' + settings.classWrap + '" style="width: ' + self.outerWidth() + 'px; height: ' + self.outerHeight() + 'px;" />');
			self.before('<span class="' + settings.classValue + '" style="padding-right: ' + settings.paddingRight + 'px;">' + initialValue + '</span>');

			if (self.is(':disabled')) {
				self.parent().addClass(settings.classDisabled);
			}

			self.on('change keypress keydown keyup update', function() {

				var _self = $(this),
					selected = _self.find('option:selected');

				_self.prev().html(selected.text());

				$(element).find('option').each(function() {
					$(this).attr('selected', false);
				});

				selected.attr('selected', true);

			});

			self.focus(function() {

				$(this).parent().addClass(classFocus);

			}).blur(function() {

				$(this).parent().removeClass(classFocus);

			});

		}

	};

	$.fn[pluginName] = function(options) {

		this.each(function() {

			if (!$.data(this, 'plugin_' + pluginName)) {

				$.data(this, 'plugin_' + pluginName, new Plugin(this, options));

			}

		});

		return this;

	};

}(jQuery, window, document));