|
| 1 | +/**! |
| 2 | + * @author Steve Piron <https://twitter.com/stevepiron> |
| 3 | + * @requires jQuery |
| 4 | + * |
| 5 | + * A jQuery plugin that resizes selects to to width of their selected option. |
| 6 | + */ |
| 7 | +(function( $ ) { |
| 8 | + |
| 9 | + var defaults; |
| 10 | + var params; |
| 11 | + |
| 12 | + // ====================================================================== // |
| 13 | + // Functions |
| 14 | + // ====================================================================== // |
| 15 | + |
| 16 | + /** |
| 17 | + * 1. Create a dummy `span` element using the ame text as the selected |
| 18 | + * (current) option. |
| 19 | + * 2. Append it to the body to get its width, then remove it. |
| 20 | + * 3. Resize the original select. |
| 21 | + */ |
| 22 | + function resizeIt( $select ) { |
| 23 | + /* [1] */ |
| 24 | + var text = $select.find('option:selected').text(); |
| 25 | + var className = (params.classes) ? ' class="'+params.classes+'"' : ''; |
| 26 | + var $dummyOption = $('<span'+className+'>').html(text); |
| 27 | + |
| 28 | + /* [2] */ |
| 29 | + $dummyOption.appendTo('body'); |
| 30 | + var width = $dummyOption.width(); |
| 31 | + $dummyOption.remove(); |
| 32 | + |
| 33 | + /* [3] */ |
| 34 | + $select.width(width + params.iconWidth); |
| 35 | + } |
| 36 | + |
| 37 | + // ====================================================================== // |
| 38 | + // Plugin |
| 39 | + // ====================================================================== // |
| 40 | + |
| 41 | + $.fn.spAutoWidthSelect = function( options ) { |
| 42 | + |
| 43 | + /** |
| 44 | + * Note: using `return` keeps jQuery's chaining possibility |
| 45 | + */ |
| 46 | + return this.each(function() { |
| 47 | + |
| 48 | + var $this = $(this); |
| 49 | + |
| 50 | + defaults = { |
| 51 | + iconWidth: 0, |
| 52 | + classes: false |
| 53 | + }; |
| 54 | + |
| 55 | + params = $.extend( defaults, options ); |
| 56 | + |
| 57 | + // ============================================================== // |
| 58 | + // On ready |
| 59 | + // ============================================================== // |
| 60 | + |
| 61 | + resizeIt( $this ); |
| 62 | + |
| 63 | + // ============================================================== // |
| 64 | + // On change |
| 65 | + // ============================================================== // |
| 66 | + |
| 67 | + $this.on('change', function(){ |
| 68 | + resizeIt( $(this) ); |
| 69 | + }); |
| 70 | + |
| 71 | + }); |
| 72 | + }; |
| 73 | + |
| 74 | +}( jQuery )); |
0 commit comments