Skip to content

Instantly share code, notes, and snippets.

@DrBrad
Created March 3, 2017 21:38
Show Gist options
  • Save DrBrad/32ceaafdf43d95773d4e02990bc6d628 to your computer and use it in GitHub Desktop.
Save DrBrad/32ceaafdf43d95773d4e02990bc6d628 to your computer and use it in GitHub Desktop.
A very simple way to highlight HTML syntax with JavaScript.
//SET AN ON UP-PRESS TO GO TO THE FUNCTION colorText(this)
function colorText(ele){
var caret = getCaretPos(ele);
var text = ele.textContent.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/=/g, '&#61;');
text = text.replace(/&lt;(.*?)(|(\s)\b(.*?)(|(&#61;)((".*?")|(\'.*?\')))(|(\s)\b(.*?)(|(&#61;)((".*?")|(\'.*?\')))))&gt;/g, '&lt;<span class="tag">$1</span>$3<span class="att">$4</span>$6<span class="par">$7</span>$11<span class="att">$12</span>$14<span class="par">$15</span>&gt;');
ele.innerHTML = text;
setCaretPos(ele, caret);
}
function getCaretPos(ele){
var caretOffset = 0;
if(typeof window.getSelection != 'undefined'){
var range = window.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(ele);
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(ele);
preCaretTextRange.setEndPoint('EndToEnd', textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
function setCaretPos(ele, pos){
var charIndex = 0, range = document.createRange();
range.setStart(ele, 0);
range.collapse(true);
var nodeStack = [ele], node, foundStart = false, stop = false;
while(!stop && (node = nodeStack.pop())){
if(node.nodeType == 3){
var nextCharIndex = charIndex + node.length;
if(!foundStart && pos >= charIndex && pos <= nextCharIndex){
range.setStart(node, pos - charIndex);
foundStart = true;
}if(foundStart && pos >= charIndex && pos <= nextCharIndex){
range.setEnd(node, pos - charIndex);
stop = true;
}
charIndex = nextCharIndex;
}else{
var i = node.childNodes.length;
while(i--){
nodeStack.push(node.childNodes[i]);
}
}
}
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment