Home > Net >  Text input remaining horizontally scrollable with "text-overflow: ellipsis" in Chrome
Text input remaining horizontally scrollable with "text-overflow: ellipsis" in Chrome

Time:12-19

I have a text input that I want to keep at a fixed width of 300px. The value of the text input is allowed to extend beyond what fits in this. When the text does extend beyond the bounds of the input I want the text to be truncated with ellipsis, but when focused the input should be horizontally scrollable.

This behaviour is all provided with text-overflow: ellipsis;. The problem is that when unfocused the input remains horizontally scrollable, but since the text is truncated it just scrolls into white space. How can I stop this from happening?

Testing the following code I get the issue in Chrome (108.0) but not Firefox or Safari. Is this just a characteristic of Chrome that can't be avoided?

<form>
  <input
    type="text"
    style="width: 300px; text-overflow: ellipsis"
    value="asdfasdflkajsdlfjalsdfkaslkdfjalskdjflkasjdflkjaldsfkjalsdfjasdfasfasdf"
  />
</form>

This is what it looks like when you scroll right: Image of unwanted behaviour.

I have tried adding overflow: hidden; and white-space: nowrap; to the input, as well as these attributes on the surrounding form, the div above the form and even a div surrounding the input within the form. All of these result in either the same behaviour or other behaviour outside of the specification described above.

There is this related question, but there is no satisfactory answer there and I have been able to narrow it down to being a Chrome problem... Input element scrollable with text-overflow ellipsis enabled

CodePudding user response:

I believe it's a known Chrome issue. You can work around it with a little bit of JavaScript, if that works for you?

You may want to look to target Chrome only.

//Locate all elements with class inputContainer
document.querySelectorAll('.inputContainer').forEach(container => {
  //Bind a click event to each of those elements (parent)
  container.addEventListener("click", function() {
    //Turn on pointer-events (defaulted to off in CSS) 
    //and focus to prevent need to double click for focus
    container.querySelector('input').style.pointerEvents = "auto";
    container.querySelector('input').focus();
  });
});

//Bind a blur event to all input fields to turn pointer-events back to "none"
document.querySelectorAll('input').forEach(input => {
  input.addEventListener("blur", function() {
    this.style.pointerEvents = "none";
  });
});
<form>
    <!-- Added container -->
    <div >
      <input type="text" style="pointer-events:none;width: 300px; text-overflow: ellipsis" value="asdfasdflkajsdlfjalsdfkaslkdfjalskdjflkasjdflkjaldsfkjalsdfjasdfasfasdf" />
    </div>
</form>

  • Related