Created
May 31, 2012 14:45
-
-
Save megamattron/2843893 to your computer and use it in GitHub Desktop.
Autogrow for textfields, as written by http://stackoverflow.com/users/21677/999 and posted in http://stackoverflow.com/questions/931207/is-there-a-jquery-autogrow-plugin-for-text-fields
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
// From http://stackoverflow.com/questions/931207/is-there-a-jquery-autogrow-plugin-for-text-fields | |
(function ($) { | |
$.fn.autoGrowInput = function (o) { | |
o = $.extend({ | |
maxWidth:1000, | |
minWidth:0, | |
comfortZone:70 | |
}, o); | |
this.filter('input:text').each(function () { | |
var minWidth = o.minWidth || $(this).width(), | |
val = '', | |
input = $(this), | |
testSubject = $('<tester/>').css({ | |
position:'absolute', | |
top:-9999, | |
left:-9999, | |
width:'auto', | |
fontSize:input.css('fontSize'), | |
fontFamily:input.css('fontFamily'), | |
fontWeight:input.css('fontWeight'), | |
letterSpacing:input.css('letterSpacing'), | |
whiteSpace:'nowrap' | |
}), | |
check = function () { | |
if (!input.val()) { | |
var placeholder = input.attr("placeholder"); | |
// console.log("Using input placeholder as val: " + placeholder); | |
val = placeholder; | |
} else if (val === (val = input.val())) { | |
return; | |
} | |
// Enter new content into testSubject | |
var escaped = val.replace(/&/g, '&').replace(/\s/g, ' ').replace(/</g, '<').replace(/>/g, '>'); | |
testSubject.html(escaped); | |
// Calculate new width + whether to change | |
var testerWidth = testSubject.width(), | |
newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth, | |
currentWidth = input.width(), | |
isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth) | |
|| (newWidth > minWidth && newWidth < o.maxWidth); | |
// Animate width | |
if (newWidth > o.maxWidth) { | |
input.width(o.maxWidth); | |
} else if (isValidWidthChange) { | |
input.width(newWidth); | |
} | |
}; | |
testSubject.insertAfter(input); | |
$(this).bind('keyup keydown blur update change', check); | |
}); | |
return this; | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment