In a web application I want to add a cool effect for text input fields - instead of limiting length with maxlength I want to dynamically highlight the part of text that exceeds the maximum length. So far I have tried this method:
<div id="highlight">
This field<span class="out-of-range"> should have 10 characters max</span>
</div>
<input type="text" value="This field should have 10 characters max">
With proper styling I made the input field transparent and the div sits exactly behind it. The div’s font colour is the same as the background (invisible) so this way I can make only the highlighted region in the span visible.
This works pretty well except one problem: when I enter more text than the field is able to contain then its content is scrolled by the browser and I need to adjust the position of the highlight accordingly. This needs to work in Safari and Firefox.
First I tried the scrollLeft property on the input element. Apparently it works only in IE, other browsers just return 0 regardless of how much text I enter.
However, it turns out that scrollLeft works very well across all browsers on textarea elements. So if I could make textarea fields appear and behave exactly as text input fields I would be able to replace them with js and all would work perfectly. This is as far as I could get in achieving this:
<html>
<head>
<title>scroll</title>
<script type="text/javascript">
function test() {
var f = document.getElementById('field');
alert(f.scrollLeft);
}
</script>
<style type="text/css">
textarea {
overflow: hidden;
resize: none;
}
</style>
</head>
<body>
<textarea id="field" cols="15" rows="1" wrap="off"></textarea>
<p><input type="button" value="test" onclick="test()"></p>
</body>
</html>
Clicking the button will show the scrolling position in the textarea. But there is one huge problem: it works well in all browsers except Firefox. With overflow: hidden Firefox doesn’t scroll the textarea at all so when I enter more text than the width allows the cursor goes out of sight and I can type blindly. This is unacceptable.
I want to achieve one of the following in Safari and FF:
- get the horizontal scrolling position of text inside input field
- make textarea behave like input field
I can also implement a completely different solution if it works well. And for usability reasons I don’t want to emulate form fields -I want real form fields so all the standard features work like tab navigation, copy by drag&drop, spell check (if a browser provides), etc.