Last active
August 29, 2015 13:56
-
-
Save magnobiet/8977126 to your computer and use it in GitHub Desktop.
jQuery Custom Select (http://codepen.io/magnobiet/pen/BFlsn)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* | |
* 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment