I have a simple replace
function that gets the value input and replace it in the text adding the same value with a span
. I'm using it to highlighting the find results, it works fine but the text is an editable div
that too have to execute the replace function if typed.
The problem is when the function was executed the caret navigation/text insertion cursor
gets back to the start of the text.
There is some manner to control this caret to execute the replace function
without changing his position inside of the text?
var txt = document.querySelector("#text");
txt.addEventListener("input", replace);
var input = document.querySelector("#input");
input.addEventListener("input", replace);
function replace() {
let re = new RegExp(input.value, 'gi');
let replace = txt.textContent.replace(re, function (e) {
let r = "<span class='highlight'>" + e + "</span>";
return r;
});
txt.innerHTML = replace;
}
.highlight {
background: #00ff90;
}
#input { padding:5px;
}
#text{
border:1px solid #ccc; padding:5px;
margin-top:5px;
width:300px;
}
The regex works fine
<input id="input" placeholder="regex" type="text" />
<p>
but when you try to type in the text box the function replace was called and the entry text move to the start, the fucntion has to be called but the text cursos should stay still<p>
<div id="text" contenteditable="true">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mattis arcu urna, at volutpat
justo ultrices eget. Ut facilisis congue scelerisque. Vivamus
</div>