Robert
Robert

Reputation: 10380

jQuery onfocus and onblur event minification

As you can see I am trying to increase the height of the text field when the user types into it and when he clicks away (element loses focus) I am making it smaller.

Is there a simpler way to write the following code?

Simple HTML input field:

<input type="text" />

jQuery:

$(document).ready(function() {

    $('input').on('focus', function() {
        $(this).height('20px');
    });

    $('input').on('blur', function() {
        $(this).height('12px');
    });

});

Upvotes: 0

Views: 226

Answers (1)

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60507

This can be done more-efficiently with just CSS, but using jQuery, you could use event delegation.

$(document).on('focus blur', 'input', function(e) {
    $(this).height(e.type === 'focusin' ? '20px' : '12px');
})

For completeness, here's the CSS solution:

input {
    height: 12px;
}
input:focus {
    height: 20px;
}

Upvotes: 1

Related Questions