0

My javascript is pretty basic so I though I'd ask the experts as to whether my current method is right or not, and if there are better, more accepted ways.

Normally I would use jquery's .on event to trigger a function, like this:

$("body").on("input", "textarea", textareaAutoGrow);

function textareaAutoGrow() {
    var pad = $(this).outerHeight(false) - $(this).innerHeight();

    this.style.height = "auto";
    this.style.height = (this.scrollHeight + pad) + "px";
}

This way, 'this' is passed automatically, however I now need to do the same thing on the window resize event for all textareas, not just one specific one.

Here's how I've done it:

$(window).on("resize", refreshAutoGrow);

function refreshAutoGrow() {
        $el = $(".text-field.autogrow").filter(function () {
            return $(this).val();
        });

        $el.each(function () {
            textareaAutoGrow.call(this);
        });
    }

I've called the textareaAutoGrow function using .call - something I picked up from looking at jquery widgets.

It works but as I said, it's very much a guess - is this the right approach, or are there more accepted ways of doing what I want?

0

1 Answer 1

1

Trigger it with each on resize to loop the textareas:

function textareaAutoGrow() {
    var pad = $(this).outerHeight(false) - $(this).innerHeight();

    this.style.height = "auto";
    this.style.height = (this.scrollHeight + pad) + "px";
}

$("body").on("input", "textarea", textareaAutoGrow);
$(window).on("resize", funtion() {
    $("textarea").each(textareaAutoGrow);
});
Sign up to request clarification or add additional context in comments.

3 Comments

first on("input" will not work on dynamic textareas you need to use the code form the question $("body").on("input", "textarea"
now the second code will not work because textareas will hold reference to body.
Ahh, sure. ;) Dumb me. I removed that part then. It would be overhead to do it in this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.