I am making a syntax highling code editor in HTML, JS, and CSS.
How it Works: There are two divs that overlap. The one on top is the one that you edit. The one below mimicks what you type, but is formatted (using prism js).
Problem:
Whenever there are consecutive line breaks (more than one line break at a time), the formatted code appears that many times below the typed text.
Example:
Typed Text:
<span></span>
<h1></h1>
Formatted:
<span></span>
<h1></h1>
Code
`#codeContainer {
position: fixed;
top: 10%;
left: 0%;
z-index: 1;
width: 100%;
height: 90%;
outline: 0;
}
#code {
position: absolute;
left: 0%;
top: 0%;
width: 100%;
height: 100%;
background-color: transparent;
font-size: 14px;
line-height: 1.5;
white-space: pre-wrap;
overflow: auto;
}
#highlight {
position: absolute;
left: 0%;
top: 0%;
z-index: 0;
width: 100%;
height: 100%;
background-color: white;
font-size: 14px;
color: white;
line-height: 1.5;
white-space: pre-wrap;
overflow: auto;
margin-top: -6px;
padding-left: 5px;
}
pre code {
position: absolute;
left: 0%;
top: 0%;
width: 100%;
height: 100%;
padding-left: 5px;
}
#code,
#highlight {
font-size: 14px;
line-height: 1.5;
font-family: 'Courier New', Courier, monospace;
}
<div id="codeContainer">
<div id="highlight"></div>
<pre id="code">
<code contenteditable="true"></code>
</pre>
</div>
const codeElement = document.getElementById('code');
const highlightElement = document.getElementById('highlight');
function updateHighlight() {
const code = codeElement.innerText;
var highlightedCode = Prism.highlight(code, Prism.languages.html, 'html');
highlightElement.innerHTML = highlightedCode.toString();
}
codeElement.addEventListener('input', updateHighlight);
I am not really sure how I could fix this, and I don't really know what is causing the issue. Any help is appreciated. Thanks!
Edit:
I made the CSS for the #code to make the text transparent, and the color for the highlighted black. This hides the typed making it seem like the right line breaks, but the line break problem still occurs.
Solution
I changed the
<div id="codeContainer">
<div id="highlight"></div>
<pre id="code">
<code contenteditable="true"></code>
</pre>
</div>
To
<div id="codeContainer">
<pre>
<div id="highlight"></div>
</pre>
<textarea name="code" id="code" cols="30" rows="10"></textarea>
</div>