Insert the text from the textarea into the style
element.
- Monitor the
input
event on the textarea to capture any new content being added.
- Attempt to locate the
style
element using the ID previewStyle
. If it exists, append the text. Otherwise, create a new style
element and add the content there.
View the live demonstration here
function render(value) {
let previewStyle = document.getElementById('previewStyle');
if(!previewStyle) {
addStyle(value);
}else {
previewStyle.innerText = value;
}
}
function addStyle(styles) {
/* Creating style element */
const css = document.createElement('style');
css.type = 'text/css';
css.id = 'previewStyle';
if (css.styleSheet){
css.styleSheet.cssText = styles;
} else {
css.appendChild(document.createTextNode(styles));
}
/* Appending style to the head tag */
document.getElementsByTagName("head")[0].appendChild(css);
}
const text = document.getElementById('txtCSS');
text.addEventListener('input', (e) => {
const content = e.target.value;
render(content);
});
render(text.value);
Consider using a library to replace the current textarea for enhanced code highlighting, such as: