syntax-highlighted-textarea-with-backend

A simple demo of how to load and save source code between a syntax-highlighted textarea and a backend database. This uses the custom <code-input> element. You can read about how to create syntax-highlighted textareas at CSS-Tricks.

View the Source for this demo (written in Node.js but you can use the same techniques with any server-side language)

Syntax highlighting by Prism.js

Loading - change the value of the textarea backend, then run the JS update function frontend

When loading code into a <code-input> custom element, fetch the code as plaintext from a database, then escape " characters by replacing them with \" so the HTML attribute is not ended early, and will not interpret double quotes as the end of the value attribute's value. Then, the value attribute of the <code-input> should be changed to the resulting text. I have updated the code-input demo to automatically update both the editable textarea and syntax-highlighted pre code to the value attribute on load.

If you are using the original demo, change the value attribute of the <textarea>, then run the original update function I showed in the article client-side.

PHP example

<code-input style="height: 500px; width: 100%; float: left;" lang="HTML" name="code" placeholder="HTML Code" value="<?php
$codeToDisplay = // Get code to display from MySQLi or equivalent
echo str_replace('"','\"',$codeToDisplay);
?>"></code-input>

Saving - use a <form> and POST requests

Using AJAX

If you want to load/save code using frontend JavaScript, use AJAX XHR requests (see this MDN link). Then, you can change the value attribute of the <code-input> (or <textarea>). You do not need to escape the code in any way when doing this.

Please note that to change the value attribute of a code-input element, you need to use setAttribute and getAttribute, like this:

/*set*/ myCodeInput.setAttribute("value", someCode);
/*get*/ someCode = myCodeInput.getAttribute("value");