Jquery/Javascript - Syntax highlighting as user types in contentEditable region
javascript, jquery, syntax-highlighting
Solution
I liked this problem and I worked very hard to solve. I believe I have finally succeeded (with a little assistance).
= UPDATED =
Piece of Code:
[...]
// formatText
formatText: function (el) {
var savedSel = helper.saveSelection(el);
el.innerHTML = el.innerHTML.replace(/<span[\s\S]*?>([\s\S]*?)<\/span>/g,"$1");
el.innerHTML = el.innerHTML.replace(/(@[^\s<\.]+)/g, helper.highlight);
// Restore the original selection
helper.restoreSelection(el, savedSel);
}
[...]
// point
keyup: function(e){
// format if key is valid
if(helper.keyIsAvailable(e)){
helper.formatText($this[0]);
}
// delete blank html elements
if(helper.keyIsDelete && $this.text()=="") {
$this.html("");
}
}
Screenshot:
JSFiddle here: http://jsfiddle.net/hayatbiralem/9Z3Rg/11/
Needed External Resources:
- http://dl.dropboxusercontent.com/u/14243582/jscalc/js/rangy-core.js
- http://dl.dropboxusercontent.com/u/14243582/jscalc/js/rangy-selectionsaverestore.js
Helper Question (thanks): replace innerHTML in contenteditable div
Regex Test Tool (thanks): http://www.pagecolumn.com/tool/regtest.htm
Problem
I'm developing a contentEditable region on my website, where users will be able to type messages to each other. ``` <div contentEditable="true" class="smartText">User types here...</div> ``` The thing is, we will have smart text inside, meaning that if a user type `@usersame` inside this div, the `@username` should be highlighted in blue if the username exist and green if he doesn't exist. And of course all of this should happen as the user types... I have no idea where to start, right now I have this: ``` $("body").on("keyup",".smartText",function(){ var $this = $(this), value = $this.html(), regex = /[^>]#\S+[^ ]/gim; value = value.replace(regex,"<span style='color:red'>$&</span>"); $this.html(value); }); ``` But the text keeps jumping (as well as the caret position) and doesn't feel like the right direction. I guess it's a little similar to JSFiddle which colors code as it finds it. I basically want the same thing as Twitter has. Here is a JSFiddle to play around with: http://jsfiddle.net/denislexic/bhu9N/4/ Thanks in advance for your help.