One way to get the result is by doing the following:
Create a textarea
will set the id
attribute to editor_back .
<textarea id="editor_back"></textarea>
Apply 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
will set the id
attribute to editor_front .
<div id="editor_front"></div>
Apply 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 div
will be below textarea
, so we set background
and color
to transparent.
Add event keypress
to 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>