Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show line numbers for a code block using JavaScript?

Here's the thing. I use 'Highlight.js' (a javascript-based automatic syntax highlighter) to syntax-highlight code on my website. But it doesn't support line numbers or zebra-striping (for alternate lines of code).

My code block is wrapped in <pre><code> blocks like this:

<pre><code>
&lt;script type=&quot;text/javascript&quot;&gt;
// Say hello world until the user starts questioning
// the meaningfulness of their existence.
function helloWorld(world) {
for (var i = 42; --i &gt;= 0;) {
alert(&#39;Hello &#39; + String(world));
}
}
&lt;/script&gt;
&lt;style&gt;
p { color: pink }
b { color: blue }
u { color: &quot;umber&quot; }
&lt;/style&gt;
</code></pre>

And the output looks like this:

Syntax Highlighted Code

Now I want to show line numbers for the code block dynamically using JavaScript. How do I do that? (Also, if possible, how do I show zebra-striping?)

Thanks.

PS: I don't know JavaScript, so please try to be as clear as possible. I will try my best to understand. Thanks.

like image 815
its_me Avatar asked Mar 24 '12 09:03

its_me


2 Answers

You could use an alternate framework such as http://alexgorbatchev.com/SyntaxHighlighter/

Or take a look here and find something that suites. http://www.1stwebdesigner.com/css/16-free-javascript-code-syntax-highlighters-for-better-programming/

like image 71
nickw444 Avatar answered Sep 28 '22 06:09

nickw444


The basic steps would be:

  1. Take the HTML inside the element.
  2. Split by newline characters (\n).
  3. For each string, add a number and a dot in front of it.
  4. Combine the strings again with newline characters.
  5. Set the string as the HTML of the element.

However, this would mess up the syntax highlighting of the syntax highlighter because it most likely won't recognize that the code has line numbers in front. So the syntax highlighter needs to provide the functionality of line numbers for you.

like image 30
Simeon Visser Avatar answered Sep 28 '22 08:09

Simeon Visser