I'm running the following code to adjust the width of an input based on the content. It works pretty well, except if I add spaces to the end, then the text moves out of the box towards the left. How can I treat the spaces like any other characters so it doesn't break the box?
$.fn.liquidWidth = function(text, font) {
if (!$.fn.liquidWidth.fakeEl) $.fn.liquidWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.liquidWidth.fakeEl.text(text || this.val() || this.text() || this.attr('placeholder')).css('font', font || this.css('font'));
var width = $.fn.liquidWidth.fakeEl.width();
if (this.data('liquid-min-width') != '' && width < this.data('liquid-min-width')) {
width = this.data('liquid-min-width');
} else if (this.data('liquid-max-width') != '' && width > this.data('liquid-max-width')) {
width = this.data('liquid-max-width');
}
if (width < 8) {
width = 8;
}
return width;
};
$(document).on('input', '.liquid-width', function() {
var inputWidth = $(this).liquidWidth();
$(this).css({
width: inputWidth
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type something followed by a bunch of spaces...</p>
<input type="text" class="liquid-width" placeholder="text">