Jurģis Toms Liepiņš Jurģis Toms Liepiņš - 1 month ago 18
jQuery Question

Span overflow when value set programmatically not typed

I have created a span on top of an input field, basically to manipulate the styling of the input text (fiddle).

It works great as long as you don't type past the input box border, or this happens: enter image description here

Now, I learned that you could have the same scrolling effect as input for the span, like this:

white-space: nowrap;
overflow: hidden;


But, since I am not typing in the span directly, but just updating the innerHTML, this has no effect.

Is there a way I can update the span, so it would treat the updates as typing?

Answer Source

You can simulate the same effect setting the scrollLeft really high property on the span as you type on it. You also need to explicitly set the same width on both the input and the span.

You can see a working Fiddle here.

I make a "fake" span, hidden and with variable width, so I can use it to set the scrollLeft property to the width the text would have if it were to behave normally.

To handle the "cursor moving" events, I check the cursor position (via @RenatoPrado), and set scrollLeft to the percentage of the width of the text. So it's working almost like a real input field, but it's still not perfect. This only triggers on keyup (keydown was not working too well), so it has a "lag". And you can't see the blinking cursor, so that's annoying. But hopefully this sets you on the right track.