I Have A Div With Contenteditable="true" And Need To Color The Numbers Entered
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 butto
Solution 1:
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)
Solution 2:
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));
elsereturndocument.createTextNode(u);
});
var caretPos = getCaretCharacterOffsetWithin(this);
$(this).empty().append(highlighted);
setCursor(this, caretPos);
});
});
functiongetCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
if (typeofwindow.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;
} elseif (typeofdocument.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;
}
functionsetCursor(node, pos) {
if (!node) {
returnfalse;
} elseif (document.createRange) {
range = document.createRange();
range.selectNodeContents(node);
range.setStart(node, pos);
range.setEnd(node, pos);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
} elseif (node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
returntrue;
} elseif (node.setSelectionRange) {
node.setSelectionRange(pos, pos);
returntrue;
}
returnfalse;
}
A working demo is available at this JS Fiddle: http://jsfiddle.net/B3PgU/
Pieces of code taken from:
Post a Comment for "I Have A Div With Contenteditable="true" And Need To Color The Numbers Entered"