My code is here on codepen
I am trying to count the characters and wrap those that exceed a certain limit in a <span> which I've styled as red.
The code mostly works with the exception of the function that moves the caret to the end, on Firefox the ranges I create there lose all their whitespaces so that 'abcd abcd' becomes 'abcdabcd'
Here is the code for the function:
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
// Modern browsers
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
// IE
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
Has anybody faced this before and found a solution ?
Firefox is ignoring white spaces in HTML. You have to modify it to replace space characters with html escape characters. In place of the code
inputText.substring(0,maxCharacter)
You should do
inputText.substring(0,maxCharacter).replace(/ /g, ' ')
Similarly in place of code
inputText.substring(maxCharacter)
You should do
inputText.substring(maxCharacter).replace(/ /g, ' ')
That will fix it. Hopefully it will work in all other browsers too.
Changed pen: http://codepen.io/anon/pen/GgXBjp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With