(IE Specific) How to detect if entered text is longer than the width of the input element
This is an IE specific issue, all versions. In all other browsers, the scrollWidth of the input element is larger than the clientWidth of the input element when text overflows.
Is there a way to determine that the text in the input field has overflowed the width bindings of the input element in IE?
Below is a simple example of checking clientWidth and scrollWidth
var myInput = document.body.querySelector('#myInput');
myInput.value = 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem';
function checkInputSize() {
alert('Client Width: ' + myInput.clientWidth + '\n' +
'Scroll Width: ' + myInput.scrollWidth);
}
<div>
<input id="myInput"></input>
</div>
<button onclick="checkInputSize()"
style="margin-top: 2em;">
<span>Display Input Size</span>
</button>
I hope there is a more direct way to define the above without requiring the styles to be replicated correctly to another element. I realize this might be the "best" option, but I really wanted to give IE the advantage of doubting it was better.
If I need to replicate styles, the best option would be to use window.getComputedStyle, although IE8 doesn't support this feature, which doesn't bother me.
var getJsStyleName = function(styleName) {
var firstCharacterRegex = new RegExp('^.');
styleName = styleName.split('-');
for (var i = 1; i < styleName.length; i++) {
styleName[i] = styleName[i].replace(firstCharacterRegex, styleName[i][0].toUpperCase());
}
return styleName.join('');
};
var copyComputedStyles = function(toElement, fromElement) {
var comStyle = window.getComputedStyle(fromElement) );
for (var i = 0; i < comStyle.length; i++) {
var styleName = getJsStyleName(comStyle[i]);
toElement.style[ styleName ] = comStyle[ styleName ];
}
return toElement;
}
var inputStyledDiv = copyComputedStyles(document.createElement('div'), inputElement);
source to share
I went through all the computed styles in IE using text that does and does not overflow the input box. All styles are identical.
An alternative is to duplicate the input content in a div and view if its clientWidth is wider than the input clientWidth. You have to be careful to duplicate all input styles in a div.
The code below iterates through myInput
currentStyle
. This property is not available in Chrome, in which case it falls back to your logic scrollWidth
> clientWidth
.
function checkInputSize() {
var contents= document.querySelector('#contents');
var output= document.querySelector('#output');
var st= myInput.currentStyle;
if(st) {
for(var i in st) {
contents.style[i]= st[i];
}
contents.innerHTML= myInput.value;
output.innerHTML= contents.clientWidth+(contents.clientWidth >= myInput.clientWidth ? ': overflow' : '');
contents.style.display= 'none';
}
else {
output.innerHTML= myInput.scrollWidth+(myInput.scrollWidth > myInput.clientWidth ? ': overflow' : '');
}
}
Fiddle
source to share