Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript range loses whitespace on Firefox?

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 ?

like image 293
George Bora Avatar asked Jun 19 '26 18:06

George Bora


1 Answers

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, '&nbsp;')

Similarly in place of code

inputText.substring(maxCharacter)

You should do

inputText.substring(maxCharacter).replace(/ /g, '&nbsp;')

That will fix it. Hopefully it will work in all other browsers too.

Changed pen: http://codepen.io/anon/pen/GgXBjp

like image 102
RaviH Avatar answered Jun 21 '26 07:06

RaviH