I am using jQuery 1.6.2
When my page loads, I run a loop that finds input fields, calculates their needed size, and resizes them. Here’s the function:
// MINIMIZE TEXT FIELDS ON LOAD
$(":text").each(function() {
var MyString = $(this).val();
var MyMax = $(this).attr("maxlength");
var MySize = minimizeText(MyString, MyMax);
$(this).attr("size", MySize);
});
The loop accesses this function:
var minimizeText = function minimizeText(MyString, MyMax) {
var MyLength = MyString.length;
var MySize = MyLength + 5;
if (MySize < MyMax && MySize < 50) {
return MySize;
} else if (MyMax > 50 ) {
return 50;
} else {
return MyMax;
}
}
If the user changes the text in the input field, the size is recalculated to fit the text in the field.
// MINIMIZE TEXT FIELDS ON KEYUP
$(":text").keyup(function() {
var MyString = $(this).val();
var MyMax = $(this).attr("maxlength");
var MySize = minimizeText(MyString, MyMax);
$(this).attr("size", MySize);
});
Both of these work perfectly well. My goal here is to condense this code and still make it readable. My question is how can I combine these two so that the text field are checked on load as well as on keyup?
Your keyup handler is the same as the function that you pass into the initial call to
.each(). You can define a single function and pass it in as an argument. eg.