Fixing the 100% width text input field
Here's the sitch:
You have a field in a container. Oftentimes, you want to simply make that field a certain percentage width of its parent container, but when you do that something weird happens: The field, like a div treats its typing area as the main area. Actually, that isn't that weird. It's very expected.
However, this is kind of a big annoyance in the design community. It means having to do things like set arbitrary pixel widths of fields to accommodate for border, padding and margin. Across a website, this can be a huge pain in the ass, especially for different field types and different containing column widths.
Behold my solution: SuperWidthField
What SuperWidthField does is allow you to set the field width by percentage, but rather than adjust the internal width of the field, it adjusts the external, or outer, width (that is, including your padding, margin and border). This allows you to, for instance, simply have a field with a 1px border and a 5px padding to occupy a space with 100% width, and not burst outside its parent container.
Here's the code:
$.fn.superWidthField = function( percentage ){
$(this).each( function(){
var input = {
paddingLeft: parseInt( $(this).css('padding-left'), 10 ),
paddingRight: parseInt( $(this).css('padding-right'), 10 ),
marginLeft: parseInt( $(this).css('margin-left'), 10 ),
marginRight: parseInt( $(this).css('margin-right'), 10 ),
borderLeft: parseInt( $(this).css('border-left-width'), 10 ),
borderRight: parseInt( $(this).css('border-right-width'), 10 ),
}
var fitTo = $(this).parent().innerWidth();
var fieldWidth = ( fitTo - ( input.paddingLeft + input.paddingRight + input.marginLeft + input.marginRight + input.borderLeft + input.borderRight ) ) * percentage;
$(this).css( 'width', fieldWidth + 'px' );
});
return this;
}
Put this function somewhere in your Javascript file (preferably outside the $(document).ready() area. Instantiate it like this (inside your $(document).ready() area:
$('.the-field').superWidthField( 1.00 );
.the-field is the selector of the element that you want to affect. in the parenthesis, you must input a percentage between 0 and 1 ( .99 would equal 99%, .18 would equal 18%, etc. ). And, of course, you can chain other functions off of it.
If you have any questions on how to implement this plugin, let me know.
Tags: jquery, javascript, formatting, plugin
Some other articles you might enjoy...
| jQuery is-or-is-child-of function | Saturday, June 25, 2011 |
| Snazzy jQuery Form Alert Boxes | Tuesday, February 9, 2010 |
| jQuery Vertical Align Function | Wednesday, October 27, 2010 |
| E-mail Newsletter Form with jQuery, AJAX, MySQL and PHP | Sunday, March 14, 2010 |
| JQuery/PHP: Simple Random Text Generation Box | Monday, June 22, 2009 |
design 16 articles
user interface 7 articles
php 7 articles
code 7 articles
web 6 articles
jquery 6 articles
tutorial 6 articles
picture 5 articles
marketing 5 articles
html 4 articles
2012
2011
2010
2009