2
\$\begingroup\$

I have a keyup function that expands an input field as text is added. There are a lot of fields where this code will be applied, what is the best way to write this for best performance?

Here is a working demo: http://jsfiddle.net/J9Ner/

$('input.name','#bakery').live('keyup', function() {
    var el = $(this);
    var len = el.val().length;

    if (len < 20) {
        el.width('200px');
        return;
    } else if (len > 56) {
        return;
    }

    el.width((len * 10) + 'px');
});
\$\endgroup\$
2
\$\begingroup\$

You can rearrange the if/else to be a little more efficient.

You can retrieve the length a little more efficiently.

And, use .delegate() (pre jQuery 1.7) or .on() (jQuery 1.7+) with a selector of a parent object close to the elements. That will perform much better than .live() for large numbers of elements.

It could look something like this:

$('#bakery').on('keyup', 'input.name', function() {
    var el = $(this);
    var len = this.value.length;

    if (len < 20) {
        el.width('200px');
    } else if (len <= 56) {
        el.width((len * 10) + 'px');
    }
});

If you don't actually need .live() or .on() type behavior, it's even more performant to avoid the need for event propagation and bind the event handlers directly to the input elements themselves so no selector matching must be done on each key event:

$('#bakery input.name').keyup(function() {
    var el = $(this);
    var len = this.value.length;

    if (len < 20) {
        el.width('200px');
    } else if (len <= 56) {
        el.width((len * 10) + 'px');
    }
});

And, then removing the jQuery .width() call would speed it up some more:

$('#bakery').on('keyup', 'input.name', function() {
    var len = this.value.length;

    if (len < 20) {
        this.style.width = '200px';
    } else if (len <= 56) {
        this.style.width = (len * 10) + 'px';
    }
});

You can see this last one working here: http://jsfiddle.net/jfriend00/7Pb8b/

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.