iMx
iMx

Reputation: 846

Why do I get wrong scrollHeight for TEXTAREA on input change in Chrome?

I'm trying to write a JavaScript for auto adjusting the text size of a textarea.

my problem is: after the line is filled, the scrollHeight returns wrong value on each second symbol (you can see the log output in the console).

The height of the textarea is 47, I get alternately 62 and 47 (and no resize).

JQuery Plugin:

; (function($) {
/**
 * Resizes the text in the textarea
 * @version 0.1
 */
$.fn.textResizer = function(options) {

    options = jQuery.extend({
        maxFontSize: null,
        minFontSize: 8,
        step: 1
    }, options);

    return this.each(function() {
        var maxHeight = $(this).outerHeight();
        $(this).bind('input propertychange', function() {

            var innerElements = $(this).children(':visible');
            console.log($(innerElements));

            var fontSize = options.maxFontSize,
                innerHeight;

            console.log('inner: '+$(this).css( "height" )+ ', max: '+maxHeight, 'outer: '+$(this).outerHeight());
            console.log(this.scrollHeight);
            do {

                innerHeight = this.scrollHeight;
                console.log(this.scrollHeight);

                fontSize = fontSize - options.step;
                $(this).css('font-size', fontSize);

            } while ((innerHeight > maxHeight) && fontSize > options.minFontSize);
        });
    });

};

})(jQuery);

CSS:

textarea {
    position: absolute;
    width:176px;
    height:47px;
    top: 4px;
    left: 60px;
    background: #666666;
    border: none;
    color: #fff;
    overflow: hidden;
    display:inline-block;
    vertical-align: middle;
    resize: none;
    padding: 0;
  }

HTML:

<script>
$(document).ready(function() {
    $('textarea').textResizer({'maxFontSize':30});
});
</script>

<textarea></textarea>

Here is my example: http://jsfiddle.net/6nhLmcge/

What can be the reason of this behavior?

Do you know other solutions/plugins for this task?

Upvotes: 3

Views: 5961

Answers (1)

Clayton Leis
Clayton Leis

Reputation: 1298

You need to update innerHeight after you change the css, not before it. http://jsfiddle.net/svt8zsx4/

           do {

               //innerHeight = $(this).innerHeight();
                console.log(this.scrollHeight);

                fontSize = fontSize - options.step;
                $(this).css('font-size', fontSize);
                innerHeight = this.scrollHeight;

            } while ((innerHeight > maxHeight) && fontSize > options.minFontSize);

Upvotes: 3

Related Questions