ncyankee
ncyankee

Reputation: 1258

Resizing font size in textarea to fit height

I'm trying to do something different than most 'resize' textarea plugins do. I am not trying to resize the actual textarea, but rather the font size in the textarea so that all of the text fits.

I basically want an 'auto' font size for a textarea. The problem lies in the fact that there are two different ways that the font needs to get 'smaller':

  1. User presses 'enter' and creates a line break
  2. User enters more text than the width of the textarea, causing it to break down

I've seen a few instances of plugins which I've modified that creates a cloned textarea or div with the same styles that you can try to measure the new 'height' and calculate a font size based on this, but it seems to always fail in Safari and Chrome, so I'm guessing the logic is a bit flawed.

Has anybody done this before or know of a plugin where it has been done?

Upvotes: 2

Views: 5097

Answers (2)

seppli
seppli

Reputation: 11

Instead of using a textarea, you could use a div with contenteditable="true".
This solution works with removing text and increasing the font-size.

html

<div class="border" id="border">
<div class="block" id="input" contenteditable="true">Click to edit</div>
</div>

css

.block {
    width:400px;
    font-size:25px;
    font-family:'Helvetica';
}
.block:focus {
    outline: none;
}
.border {
    border: 1px solid #000;
    width:400px;
    height: 200px;
    padding: 5px;
    cursor:text;
}

jQuery

$('#border').click(function(){
    $('#input').focus();
});

$('#input').keyup(function(event){
    while ( $(this).height() > 200) {
        $(this).css('font-size', '-=1');
    }
    if (event.keyCode == 8 || event.keyCode == 46) {
        while ( $(this).height() <= 200 && $(this).css('font-size') <= "25px") {
            $(this).css('font-size', '+=1');
        }
            $(this).css('font-size', '-=1');
    }
});

Example

http://jsfiddle.net/gwyqsk0s/

Upvotes: 1

elclanrs
elclanrs

Reputation: 94141

Try this it should work but I'm not sure about performance tho:

html

<textarea></textarea>

css

textarea {
    height: 100px;
    width: 200px;
    resize: none;
    font-size: 18px;
    overflow-y: hidden;
}

jQuery

$('textarea').keypress(function(){
    if ( $(this).get(0).scrollHeight > $(this).height() ) {
        $(this).css('font-size', '-=1');
    }
});

example

http://jsfiddle.net/XCXJb/1/

Upvotes: 5

Related Questions