Created
March 3, 2017 21:38
-
-
Save DrBrad/32ceaafdf43d95773d4e02990bc6d628 to your computer and use it in GitHub Desktop.
A very simple way to highlight HTML syntax with JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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, '<').replace(/>/g, '>').replace(/=/g, '='); | |
text = text.replace(/<(.*?)(|(\s)\b(.*?)(|(=)((".*?")|(\'.*?\')))(|(\s)\b(.*?)(|(=)((".*?")|(\'.*?\')))))>/g, '<<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>>'); | |
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