Created
June 7, 2016 19:24
-
-
Save gilbert/81f957044e6786922fe3153f94b3007e to your computer and use it in GitHub Desktop.
JavaScript DOM: Render line numbers on pre with no dependencies
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
<!DOCTYPE html> | |
<head> | |
<link rel="stylesheet" type="text/css" href="line-numbers.css"> | |
</head> | |
<body> | |
<pre><code>function add (a, b) { | |
return a + b; | |
}</code></pre> | |
<script src="render.js"></script> | |
<script type="text/javascript"> | |
renderLineNumbers( document.querySelector('pre') ) | |
</script> | |
</body> | |
</html> |
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
.line-numbers-wrapper { | |
position: relative; | |
padding-left: 0; | |
} | |
.line-numbers-wrapper > code { color: #bbb; } | |
.line-numbers-code { | |
margin: 0; | |
padding: 0; | |
overflow: visible; | |
position: absolute; top: 0px; left: 3.3rem; // You may have to adjust this | |
z-index: 1; | |
// App-specific anti-styles | |
border: none; | |
} |
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
function renderLineNumbers (pre) { | |
var offsetTop = window.getComputedStyle(pre, null).getPropertyValue('padding-top'); | |
pre.classList.add('line-numbers-code'); | |
// Add class after clone | |
var wrapper = document.createElement('pre'); | |
wrapper.classList.add('line-numbers-wrapper'); | |
// Create line numbers | |
var lines = pre.innerHTML.split('\n'); | |
if ( lines[lines.length-1] === '</code>' ) { | |
var closingTag = lines.pop(); | |
lines[lines.length-1] += closingTag; | |
} | |
wrapper.innerHTML = | |
'<code>' + | |
lines | |
.map(function (_, i) { | |
return padLeft( (i+1) + '│', 4 ) | |
}) | |
.join('\n') | |
+ '</code>' | |
; | |
pre.style.top = offsetTop; // Offset clone by whatever padding you have set in app | |
pre.parentNode.replaceChild(wrapper, pre); | |
wrapper.appendChild(pre); | |
} | |
function padLeft (str,l) { return Array(l-str.length+1).join(" ") + str; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in
line-numbers.css:11
you have to change the comment fromto
because CSS doesn't support single-line comments ended by newline, it just supports block comments.
And please don't forget the opening
html
tag inexample.html:2
...