Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[WIP] Make `textarea` syntax highlight
var script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.5.1/prism.js';
document.body.appendChild(script);
var csslink = document.createElement('link');
csslink.setAttribute('rel', 'stylesheet');
csslink.setAttribute('type', 'text/css');
csslink.setAttribute('href', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.5.1/themes/prism-solarizedlight.css');
document.getElementsByTagName('head')[0].appendChild(csslink);
function checkLoadPrism() {
if (!window.Prism) {
setTimeout(() => {
checkLoadPrism();
}, 100);
} else {
renderPrism();
}
}
function renderPrism() {
var textareas = document.getElementsByTagName('textarea');
Array.from(textareas).forEach((textarea) => {
let preEl = document.createElement('pre');
preEl.setAttribute('contenteditable', true);
preEl.setAttribute('class', 'language-html');
preEl.textContent = textarea.value;
textarea.parentNode.replaceChild(preEl, textarea);
Prism.highlightElement(preEl);
preEl.addEventListener('input', (e) => {
preEl = e.target;
Prism.highlightElement(preEl);
});
});
}
checkLoadPrism();
@shark0der

This comment has been minimized.

Copy link

commented Oct 30, 2016

The caret position is reset after each keypress =/. Thanks anyway

@pawelpodkowa

This comment has been minimized.

Copy link

commented Oct 6, 2017

works fine, but how to handle it to save ?

@coolpage5

This comment has been minimized.

Copy link

commented Jan 20, 2019

I have the same problem as shark0der

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.