Javascript Function to Add Line Numbers to Code Block

Created: April 10, 2013
Last Modified: January 3, 2017
Subscribe to Internet Tips and Tools Feed

This Javascript function adds line numbers to a code block in a pre tag on your webpage. This is so you can display your javascript, C, PHP, HTML, Python or other source code on your page with line numbers for users to easily see and grab the code. It is tested to work with IE 6,7,8,9, Chrome, Safari and Firefox.

This function does not rely on CSS3 counters because CSS3 is not compatible with Internet Explorer 8 and below. Instead it uses a technique of html ordered list <ol> but when the code is selected it does not copy the line numbers because the code is layered on top of the line numbers and is therefore not copied. dlc_b

Download

Downloaded 0 times.
Please make a donation to reveal the download link.

Put your source code between <pre> </pre> tags like the ones below because HTML pre tags preserve tabs and new lines:

<pre id="preview" style="width: 100%; height: 12em; border: 1px solid black; overflow: scroll; -ms-overflow-x: scroll; overflow-x: scroll; font-family: monospace; tab-size: 3; -moz-tab-size: 3; -o-tab-size: 3; -webkit-tab-size: 3;">
<!-- Your source code goes here -->
</pre>
function line_numbers(el)
{	
	/* This function creates line numbers on source code in a pre tag
		by using ordered list <ol> tag and <li> for each line of code
		but the old code is layered on top of the ordered list so that
		when you copy and paste the code the tabs are preserved and you 
		don't copy the line numbers. 
		Created by Jeff Baker on April 5, 2013
		Copyright (C) 2013 Jeff Baker
		http://www.seabreezecomputers.com/syntax/
		
		Call the function like this:
		line_numbers(document.getElementById('line_nums')); 
	*/
	var lines = el.innerHTML.split('\n'); // split contents by newline
	el.style.position = "relative"; // Make the pre tag a relative element
	//el.style.margin = "1em";
	el.style.padding = "0";
	
	// Create another element that has identical style and innerHTML by copying el
	var cloned = el.cloneNode(true);
	cloned.style.position = "absolute"; // Absolute so we can put cloned element on top of old pre
	cloned.style.zIndex = 1; // You may have to increase the zIndex if you are using z-index other places
	cloned.style.top = '0px'; // Position on top of old element
	cloned.style.left = '3em'; // Position a little to the left.
	cloned.style.backgroundColor = "#EEEEEE"; // Add a background color
	cloned.style.height = 'auto';
	cloned.style.width = 'auto';
	cloned.style.overflow = "visible";
	
	el.id = "old_"+el.id; // Change id of pre tag to "old_id"

	// Now add an Ordered List to the contents
	if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) // Chrome cuts off 3 digit line numbers on the left
		var new_contents = "<ol style='margin-left: .5em'>"; // if we don't add a .5em margin
	else
		var new_contents = "<ol>";
	for(var i=0; i<lines.length; i++)
	{
		new_contents += "<li><pre style='display: inline; visibility: hidden;'>"+lines[i]+"</pre></li>";
	}
	new_contents += "</ol>";
	
	el.innerHTML = new_contents; // Put the ordered list into the old element
	el.appendChild(cloned); // Add the new cloned element to the old element

} // end function line_numbers(el)

Here is a "Select All/Copy to Clipboard" button like the one above for your users to easily copy the code:

<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">

if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4))
{
	// if Internet Explorer 4 or above	
	document.write('<INPUT TYPE="BUTTON" onClick="selectElementContents(document.getElementById(\'preview\'));" VALUE="Copy to Clipboard">');
}
else // if netscape or firefox
{
	document.write('<INPUT TYPE="BUTTON" onClick="selectElementContents(document.getElementById(\'preview\'));" VALUE="Select All"> then type CTRL-C to copy');
}

function selectElementContents(el) 
{
    /* http://stackoverflow.com/questions/8019534/how-can-i-use-javascript-to-select-text-in-a-pre-node-block */
	if (window.getSelection && document.createRange) {
        // IE 9 and non-IE
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.body.createTextRange) {
        // IE < 9
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.select();
        textRange.execCommand("Copy");
    }
} // end function selectElementContents(el) 

</SCRIPT>

History

ver 1.1 - 7/29/2013 - Bug fix for Chrome on lines 33 and 34

ver 1.0 - 04/05/2013 - created line_numbers javascript function

Also check out:
Online Syntax Highlighter
HTML Entity to Text Converter
HTML Tag and Attribute Stripper
Sea Breeze Computers Home Page

Copyright © 2013 by Jeff Baker

Last updated on
Created on

Back to www.seabreezecomputers.com
Subscribe to Internet Tips and Tools Feed        

User Comments

There are 0 comments.

Displaying first 50 comments.