I'm building a simple note-taking tool where certain keywords will automatically highlight as the user types so that they can easily find them later.
I've created a keyup()
function that listens to a text area and captures the existing content, but I'm unsure how to highlight all new and existing occurrences of a word (or array of words).
Here's what I have so far: https://jsfiddle.net/JonMoore/r18v7wpz/44/
$("#txt").keyup(function() {
var keyword = "test";
var txt = $(this).val();
$("#page").text(txt);
var pos = $("#page").text().search(keyword);
var pageTxt = $("#page").text();
if(pos >= 0) {
pageTxt.substr(pos, keyword.length).replace('<span class="highlight">' + keyword + '</span>');
console.log("Ran!");
}
});
This only seems to be capturing the first occurrence of the word, albeit still not highlighting like it should. If it's a partial match, the entire word should be highlighted (e.g. "testing" should also highlight for the keyword "test").
A stretch goal would be to define an array of multiple keywords and/or phrases, each of which will be highlighted appropriately, ideally in a different color.
Any help would be greatly appreciated!
You should use /test/g
instead of .replace()
Here is a sample which works for your case:
$("#txt").keyup(function() {
var txt = $(this).val();
var keyword = "test";
if (txt.indexOf(keyword) > -1){
$("#page").html(txt.replace(/test/g,'<span class="highlight">' + keyword + '</span>'));
}
else {
$("#page").html(txt);
}
});
body {
margin:0;
padding: 0;
font-family: Inter, sans-serif !important;
}
textarea {
padding: 12x;
font-family: Inter, sans-serif;
font-size: 2em;
height: 1.4em;
}
.highlight {
color:red !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea name="" id="txt" cols="30" rows="10"></textarea>
<div id="page"></div>