-3

Here is my code that works well for coloring the numbers in editable div but the cursor is going to the start of the div and it should work normal when I press keyboard arrow buttons to traverse the string, also when i click "home" and "end" buttons, cursor should go as expected

jQuery(document).ready(function(){

       $("#richTextField").keyup(function() {

          var divContent = $(this).text();

          var pattern = /(\d)/g;

          var replaceWith = '<span class="numberClass"'+ '>$1</span>';


          var highlighted = divContent.replace(pattern,replaceWith);


          $(this).html(highlighted);

       });

    });
just somebody
  • 18,602
  • 6
  • 51
  • 60
RamSafari
  • 61
  • 1
  • 5

2 Answers2

1

The following does what you want:

jQuery(document).ready(function () {

    $("#richTextField").keyup(function () {

        var divContent = $(this).text().split('');
        var pattern = /(\d)/;
        var replaceWith = '<span class="numberClass"' + '>$1</span>';
        var highlighted = divContent.map(function (u) {
            if (pattern.test(u)) return $(u.replace(pattern, replaceWith));
            else return document.createTextNode(u);
        });

        var caretPos = getCaretCharacterOffsetWithin(this);

        $(this).empty().append(highlighted);

        setCursor(this, caretPos);
    });
});

function getCaretCharacterOffsetWithin(element) {
    var caretOffset = 0;
    if (typeof window.getSelection != "undefined") {
        var range = window.getSelection().getRangeAt(0);
        var preCaretRange = range.cloneRange();
        preCaretRange.selectNodeContents(element);
        preCaretRange.setEnd(range.endContainer, range.endOffset);
        caretOffset = preCaretRange.toString().length;
    } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        var preCaretTextRange = document.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
    }
    return caretOffset;
}

function setCursor(node, pos) {
    if (!node) {
        return false;
    } else if (document.createRange) {
        range = document.createRange();
        range.selectNodeContents(node);
        range.setStart(node, pos);
        range.setEnd(node, pos);
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    } else if (node.createTextRange) {
        var textRange = node.createTextRange();
        textRange.collapse(true);
        textRange.moveEnd(pos);
        textRange.moveStart(pos);
        textRange.select();
        return true;
    } else if (node.setSelectionRange) {
        node.setSelectionRange(pos, pos);
        return true;
    }
    return false;
}

A working demo is available at this JS Fiddle: http://jsfiddle.net/B3PgU/


Pieces of code taken from:

https://stackoverflow.com/a/4812022/1662998

https://stackoverflow.com/a/2920149/1662998

Community
  • 1
  • 1
Nathan Wall
  • 10,530
  • 4
  • 24
  • 47
  • Hi Nathan, your solution does look perfect. Thanks for your time on this. However, I noticed a issue which needs to be resolved in my case. When I try to use "Shift+Home" or "Shift+end" key words combination, this solution is not working as the cursor is not moving as expected. It does not allow you to select the text as the cursor is going to the end position. Could you please suggest on this. – RamSafari Nov 24 '12 at 17:59
0

elimate the keys that you don't want to run the function, something like this (i.e. should just behave as normal)

$("#richTextField").keyup(function(e) {
    var excludeKeyCodes = [8, 9, 13, 46, 35 ,36 ,37, 38, 39, 40];
    if( !$.inArray(e.which, excludeKeyCodes ))
    {
        var divContent = $(this).text();
        var pattern = /(\d)/g;
        var replaceWith = '<span class="numberClass"'+ '>$1</span>';
        var highlighted = divContent.replace(pattern,replaceWith);        
        $(this).html(highlighted);
    }
});

for reference javascript key codes

quick summary

8 - Backspace, 9 - Tab, 13 - Enter, 46 - delete, 35 - end, 36 - home, 37,38,39,40 - arrows (left,up,right,down)

OJay
  • 4,763
  • 3
  • 26
  • 47
  • Hello Ojay, thanks for replying to my question. Your solution could b e useful for me in some scenarios but not in this case. When we try to modify the inner html or append some html tags to the editable div contents then the default behavior changes as the cursor position goes to the start of the div even we skip the above function for some key kodes. Hope you understand my problem. Here is the working demo. http://jsfiddle.net/kaPba/2/Take a look and let me know your suggestions. – RamSafari Nov 24 '12 at 17:51