0

I managed to write an angular directive (I have extracted it to pure jQuery for this post) to auto-adjust the width of a text input.

However, it seems like the width of the input field is not changing fast enough because the contents scroll back and forth.

Type into the input field to see for yourself: Demo on JSFiddle

Here is the code:

var $element = $('#my-input');

// create dummy element to calculate text width in pixels
var dummy = $('<span></span>');
$('body').append(dummy);
dummy.css('visibility', 'hidden');

// apply all relevant text styling from our input element
dummy.css('fontFamily', $element.css('fontFamily'));
dummy.css('fontSize', $element.css('fontSize'));
dummy.css('fontWeight', $element.css('fontWeight'));
dummy.css('letterSpacing', $element.css('letterSpacing'));

var resize = function() {
    dummy.html($element.val().replace(/ /g, '&nbsp;'));
    $element.width(dummy.innerWidth() + 1); // it's 1px off for some reason
};

resize();
$element.on('keyup', resize);

How can I prevent this from happening? I've already experimented some with scrolling the input field but to no success. Anybody have an idea?

anotherdave
  • 6,656
  • 4
  • 34
  • 65
Macks
  • 1,696
  • 5
  • 23
  • 38

1 Answers1

1

The keyup that you use is triggered only when the user release its keyboard key, so only after that the character is added on the input field and its content is bigger than its width. It cause the jiggeling you talk about.

You should add the input event to your listener event list. This event, supported only by new browsers, is triggered everytime a character is changed in the input field.

You can check this answer about input field change events to learn more.

Community
  • 1
  • 1