Skip to content

Instantly share code, notes, and snippets.

@zackperdue
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zackperdue/b11f3325eb6f98d94574 to your computer and use it in GitHub Desktop.
Save zackperdue/b11f3325eb6f98d94574 to your computer and use it in GitHub Desktop.
Matchlength.js

Matchlength.js

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)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment