Gineer
Gineer

Reputation: 2408

Reduce the size of the text in a TextArea as you type with jQuery

I have a really nice little function that reduces the text size inside some div's when they are displayed on the screen if they start overflowing.

$(function(){
    $('div.Body').each(function (index) {
        if ($('div.Body')[index].scrollHeight > 150) {
            $('div.Body')[index].style.fontSize = 'small';
            if ($('div.Body')[index].scrollHeight > 150) {
                $('div.Body')[index].style.fontSize = 'x-small';
                if ($('div.Body')[index].scrollHeight > 150) {
                    $('div.Body')[index].style.fontSize = 'xx-small';
                }
            }
        }
    });
})

I wanted to use the same/similar function to do the same while the users are typing the text into a textArea when they are submitting the text, but the textArea doesn't seem to have a function for scrollHeight:

$(function() {
    window.status = $('.TextAreaClass').scrollHeight;
});

This function just returns undefined.

How can I accomplish this in a textArea?

Upvotes: 1

Views: 124

Answers (2)

Cerbrus
Cerbrus

Reputation: 72967

Simply use this, instead of getting $('div.Body')[index] for each iteration of the loop:

$('div.Body').each(function () { // Remove the redundant parameter
    if (this.scrollHeight > 150) {
        this.style.fontSize = 'small';
        if (this.scrollHeight > 150) {
            this.style.fontSize = 'x-small';
            if (this.scrollHeight > 150) {
                this.style.fontSize = 'xx-small';
            }
        }
    }
});

In the .each, this refers to $('div.Body')[index].

And, like Rory said, $('.TextAreaClass') returns a jQuery object. You'll probably want to use $('.TextAreaClass')[0]; to access the first DOM element in that object.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337713

scrollHeight is a native javascript method, not a jQuery one so you will need to do the following to get the scrollHeight of the textarea:

window.status = $('.TextAreaClass')[0].scrollHeight;

Note the [0] which returns the first element in the jQuery object, which is the native DOM element. Also, you should really be caching the selected element in your current code to make it perform better. Try this:

$('div.Body').each(function (index) {
    var div = $('div.Body')[index];
    if (div.scrollHeight > 150) {
        div.style.fontSize = 'small';
        if (div.scrollHeight > 150) {
            div.style.fontSize = 'x-small';
            if (div.scrollHeight > 150) {
                div.style.fontSize = 'xx-small';
            }
        }
    }
});

Finally, the logic of that code seems flawed, as all the conditions are checking > 150?

Upvotes: 0

Related Questions