One way to get the result is by doing the following:
Create a textarea
I’ll set the attribute id
as editor_back.
<textarea id="editor_back"></textarea>
Apply the CSS
#editor_back {
color: transparent;
background: transparent;
border: 1px solid #ccc;
position: absolute;
padding: 10px;
z-index: 5;
height: 250px;
width: 250px;
font-family: 'Verdana';
font-size: 0.875em;
}
Create a div
I’ll set the attribute id
as editor_front.
<div id="editor_front"></div>
Apply the CSS
#editor_front {
background: #e9e9e9;
border: 1px solid #ccc;
padding: 10px;
position: absolute;
z-index: 1;
height: 250px;
width: 250px;
font-family: 'Verdana';
font-size: 0.875em;
}
Note that the div
will be below the textarea
, so we define the background
and color
as transparent.
Add the event keypress
in textarea
editor_back.addEventListener('keyup', function(e) {
txt = editor_back.value;
var y = txt.replace(/(function\s)([a-z]*)(\(\))/g, '<span class="func">function </span><span class="func_name">$2</span><span class="par">()</span>');
y = y.replace(/(\s?)function\s/g, '<span class="func">$1function </span>');
y = y.replace(/(\s?)\(\)/g, '<span class="par">$1()</span>');
editor_front.innerHTML = y
});
See working:
var txt = "";
var editor_front = document.querySelector('#editor_front');
var editor_back = document.querySelector('#editor_back');
editor_back.addEventListener('keyup', function(e) {
txt = editor_back.value;
var y = txt.replace(/(function\s)([a-z]*)(\(\))/g, '<span class="func">function </span><span class="func_name">$2</span><span class="par">()</span>');
y = y.replace(/(\s?)function\s/g, '<span class="func">$1function </span>');
y = y.replace(/(\s?)\(\)/g, '<span class="par">$1()</span>');
editor_front.innerHTML = y
});
#editor_front {
background: #e9e9e9;
border: 1px solid #ccc;
padding: 10px;
position: absolute;
z-index: 1;
height: 250px;
width: 250px;
font-family: 'Verdana';
font-size: 0.875em;
}
#editor_back {
background: transparent;
border: 1px solid #ccc;
color: transparent;
position: absolute;
padding: 10px;
z-index: 5;
height: 250px;
width: 250px;
font-family: 'Verdana';
font-size: 0.875em;
}
span.func {
color: red;
}
span.func_name {
color: #069;
font-weight: bold;
}
span.par {
color: green;
}
#ver_html {
bottom: 0;
position: absolute;
}
<div id="editor_front"></div>
<textarea id="editor_back" cols="30" rows="10"></textarea>
textarea
does not accept elements, only text. Therefore you cannot style parts of the text other than the whole text.– Sam