2

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">
Barmar
  • 741,623
  • 53
  • 500
  • 612
SeaBass
  • 1,584
  • 4
  • 20
  • 46

2 Answers2

3

That won't work as is, because when you add space to a standard HTML element, it only render one, no matter how many you put in a row, which is quite different for e.g. an input, which renders them all.

For your span to also size like an input, use white-space: pre

or replace its "space"'s with &nbsp;

Stack snippet

$.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
 });
});
span {
  white-space: pre
}
<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">
Asons
  • 84,923
  • 12
  • 110
  • 165
1

You have to set white-space:pre on your span - then it should work

Halko Karr-Sajtarevic
  • 2,248
  • 1
  • 16
  • 14