CodeBox

This library provides a code editor element for webpages. It supports syntax coloring, parenthesie matching, line numbering, and block indentation.

Here is a live demo of a CodeBox editor. Use the drop-down box to change the language used for syntax highlighting.

The library converts HTML textarea or input elements to code editors when they have the class "codebox", but if the library fails to run, perhaps if JavaScript is off or blocked due to a policy, the original HTML element is still there as a fallback for editing the code as plain text.


⇓ Download Zip (10 KB)  (Open Source - MIT License)

Project Files:

Overview

CodeBox is a lightweight code editor for webpages. It extends the functionality of the native HTML textarea elements by making the text invisible, and rendering the formatted code behind it in a div element. As a result, it operates transparently, since the textarea still exists and contains a copy of the code. However, this simple approach does have one downside: It's asymptotically slow. If you need to edit large code files, another editor may be more suitable. This was designed for small scripts, math equations, and shaders, and that's where it shines.

Usage

Simply include the script file, and add the class "codebox" to any textarea or input element, and it will be turned into a CodeBox when the page loads. For example:

<textarea id="mybox" class="codebox linenums" data-syntax="js"></textarea>

The language of the code is specified in a data-syntax attribute:

Languagedata-syntax name
JavaScriptjs
HTML Documenthtml
CSScss
PHPphp
GLSL Shaderglsl
Math Expressionsmath

Class Options

You can add additional class names to change the settings of the codebox:

linenums

Enables a display of line numbers on the left edge.

dark

Shows the code in dark mode.

Functions

function getCode(codebox, code);

Gets the code string in a CodeBox. Always use this function instead of the usual value property. It will work whether or not the code editor was initilized or the original HTML textarea element is still there.

function setCode(codebox, code);

Sets the code string in a CodeBox. Always use this function to set the contents of the box. It will work whether or not the code editor was initilized or the original HTML textarea element is still there.

function initCodeBoxes();

Call this if you add new elements to the document with the "codebox" class that you want initialized as CodeBox editors.

function refreshCodeBox(codebox);

Refreshes the formatting and syntax coloring in a CodeBox.

function getCodeBox(codebox);

Returns the textarea or input element that contains the code.

function setCodeSyntax(codebox, syntax);

Changes the syntax used for formatting the code. This changes the data-syntax attribute, but it will work regardless of whether the CodeBox has been initialized yet or not.