Attach this plugin to an input field and it matches the width of the field to the number of characters in the field. Great for inline editable text fields!
$('input').matchlength()
| // jQuery Plugin created by Zack Perdue | |
| // http://zackperdue.com | |
| // jshint asi: true | |
| var MatchLength = function(element){ | |
| this.element = element | |
| this.defaults = { | |
| size: parseInt($(this.element).attr('size')) || ($(this.element).attr('placeholder')||'').length || 8 | |
| } | |
| this.init() | |
| } | |
| MatchLength.prototype = { | |
| init: function(){ | |
| this.resizeInput() | |
| $(this.element).on('keydown keyup change focusout', function(){ | |
| this.resizeInput() | |
| setTimeout(function(){ | |
| this.resizeInput() | |
| }.bind(this), 0) | |
| }.bind(this)) | |
| }, | |
| resizeInput: function(){ | |
| $(this.element).attr('size', $(this.element).val().length || this.defaults.size) | |
| } | |
| } | |
| $.fn.matchlength = function(){ | |
| this.each(function(){ | |
| new MatchLength(this) | |
| }) | |
| } |