/$$$$$$$ /$$$$$$$$ | $$__ $$| $$_____/ | $$ \ $$| $$ | $$ | $$| $$$$$ | $$ | $$| $$__/ | $$ | $$| $$ | $$$$$$$/| $$$$$$$$ |_______/ |________/ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$$$ /$$__ $$ /$$__ $$| $$__ $$| $$_____/ | $$ \__/| $$ \ $$| $$ \ $$| $$ | $$ | $$ | $$| $$ | $$| $$$$$ | $$ | $$ | $$| $$ | $$| $$__/ | $$ $$| $$ | $$| $$ | $$| $$ | $$$$$$/| $$$$$$/| $$$$$$$/| $$$$$$$$ \______/ \______/ |_______/ |________/ Building a Highlighted Text Editor in the Browser ===================================================== Edited: May 4th 2025 Written by Mason Wright ===================================================== Trying to get highlighted code to be editable on your website can be tricky to implement. The idea behind successfully doing it is to display a code tag and highlight the code in there, then overlay a textarea with the font color and background set to transparent. Now that you know what we will build, let's learn how to implement it. Code Highlighting We will need to highlight the code in the editor we are building, so for this, we will use the library I use, and the most popular, highlight.js. Importing All of the code we will go over here will be in the browser, but highlight.js is an NPM package, so we can use unpkg to host our files. Highlight.js needs at least two files, the javascript and the CSS styling. If you want to use a non-default CSS layout, you can pick one from: https://highlightjs.org/static/demo/ +---------------------------------------------------+ | | | | | | +---------------------------------------------------+ Default CSS +---------------------------------------------------+ | | | | | | +---------------------------------------------------+ Custom CSS +---------------------------------------------------+ | | | | | | +---------------------------------------------------+ Custom Bundles If you know what languages you want to highlight, you can reduce the amount of javascript shipped to the browser by using highlight.js custom tool to assemble a bundle. Go https://highlightjs.org/download/ and select which languages you will be using, then download the zip file and extract the highlight.min.js file. Structure For reference, this tutorial is based on this: https://decode.sh/building-a-code-pen-type-editor-from-scratch so we will carry over some of the same concepts like adding the data-lang attribute and using a custom attribute to define our component. +---------------------------------------------------+ | | |
|
|
|
|
|
| |
| |
| Hello
|
|
|
|
|
| |
| |
| |
| h1 { |
| color: red; |
| } |
|
|
|
|
| |
| |
| |
| document.querySelector("h1") |
| .innerText += " World"; |
|
|
|
|
| |
|