blog about graphic design, web design and marketing

The D. Drew Design Blog
1
jul 11

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...