Repository: wstaeblein/texthighlighter
Branch: main
Commit: ed7a199d358b
Files: 5
Total size: 23.5 KB
Directory structure:
gitextract_mzocae5i/
├── LICENSE
├── README.md
├── index.html
├── texthighlighter.css
└── texthighlighter.js
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2023 Walter Staeblein
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# Text Highlighter
Vanilla JS class to highlight search results in a textarea while maintaining the area's functionality.
Since one can't style the text in a textarea, as it is not HTML, this class comes to the rescue allowing you to highlight any text in a textarea. Such as in search results.

#### [CHECK OUT THE DEMO](https://wstaeblein.github.io/texthighlighter/){:target="_blank"}
## Features
- No dependencies.
- No configuration. Just instantiate the class and call a method.
- Can be used in as many textareas as needed, just instantiate for each one.
- Responsive. The markings will adjust to screen size, textarea size and scroll.
- Keeps the original background from the textarea.
- Can be properly destroyed. Will remove all events and structure.
- Can choose between case sensitive and insensitive search.
- Can search freely or words only.
- Provides a count of how many results were found.
- Can navigate the search results, bringing them to view as needed.
Its use is very straightforward, instantiate the class for the textarea you need and call the search method to highlight the text you pass in the first argument. The second argument is optional and takes a boolean that if true will make the search case sensitive. The default is case insensitive. The last argument also takes a boolean that, if true, will perform a word search. Otherwise it's a free search, where any part of words can be matched.
## Usage & Code Examples
Add the following files to your project:
- texthighlighter.js
- texthighlighter.css
```javascript
let tarea = document.getElementById('txt');
let hilite = new textHighlight(tarea);
let searchResult = 'Some Expression';
let sens = true; // Case sensitive. Optional, default: false
let word = true; // Perform a words only search. Optional, default: false
hilite.search(searchResult, sens, word);
```
To access how many occurrences were found, use:
```javascript
let count = hilite.count();
```
You can navigate back and forth among the highlighted results using the prev and next methods. This navigation is cyclic, this means when the end is reached the next call takes you back to the begining and vice versa. Example below:
```javascript
let btnPrev = document.getElementById('prev');
let btnNext = document.getElementById('next');
btnPrev.addEventListener('click', hilite.prev);
btnNext.addEventListener('click', hilite.next);
```
Should you need to clear out the highlights, call the clear method.
```javascript
hilite.clear();
```
When it falls out of scope, just call the destroy method and all will be as it was before instantiation.
```javascript
hilite.destroy();
```
## About
This class was inspired by lonekorean's [highlight-within-textarea](https://github.com/lonekorean/highlight-within-textarea) JQuery plugin. Basically, I needed a similar functionality for a project but didn't want to include JQuery just for that and didn't find any other such code that was good enough.
The main aim here was to provide highlighting for search results in a textarea.
This class was tested in Chrome 117 and Firefox 118.
## Licence
This project is licensed under the [MIT Licence](https://github.com/wstaeblein/texthighlighter/blob/main/LICENSE)
================================================
FILE: index.html
================================================
<!DOCTYPE html>
<html lang="pt">
<head>
<title>Highlight Textarea Component</title>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/png" href="favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bungee&family=Open+Sans:wght@400&display=swap" rel="stylesheet">
<link href="./texthighlighter.css" rel="stylesheet">
<script src="texthighlighter.js"></script>
<style>
body {
font-family: 'Open Sans', sans-serif;
color: #0a4ba0;
}
h1 {
font-family: 'Bungee', sans-serif;
text-transform: uppercase;
text-shadow: -1px -1px 0 #0a4ba0, 1px -1px 0 #0a4ba0, -1px 1px 0 #0a4ba0, 1px 1px 0 #0a4ba0;
font-size: 54px;
color: #fffffd;
margin: -45px 0 0;
letter-spacing: 3px;
}
main {
max-width: 1000px;
width: 100%;
margin: 20px auto;
}
main > div {
margin-top: -2.2em;
}
button {
border: 1px solid #0a4ba0;
background-color: #bbb7ff;
color: #fff;
text-transform: uppercase;
font-size: 12px;
font-weight: bold;
cursor: pointer;
text-shadow: 1px 1px 0 #222;
padding: 10px 15px 7px;
transition: all 0.4s ease;
}
button:hover {
background-color: #0a4ba0;
color: #fff;
}
textarea {
width: calc(100% - 34px);
height: 350px;
padding: 8px 16px;
font-size: 18px;
color: #444;
margin-top: 10px;
background-color: #ffffe1;
scroll-behavior: smooth;
}
hr {
margin: 30px 0;
border-style: solid;
}
div#txtbox {
padding: 2px 5px;
border: 1px solid #eee;
outline: none;
display: inline-block;
width: 244px;
white-space: nowrap;
overflow: hidden;
}
input[type=text] {
max-width: 250px;
padding: 5px 10px;
font-size: 16px;
}
select {
padding: 6px 10px;
font-size: 16px;
}
nav {
margin: 0;
display: flex;
flex-wrap: wrap;
gap: 20px;
}
nav > span {
display: inline-block;
margin-bottom: 5px;
}
nav > span#hoppers {
white-space: nowrap;
}
nav > span.clear {
flex-grow: 1;
text-align: right;
}
.count {
font-size: 14px;
}
.hidden {
display: none;
}
.smalltitle {
margin-top: 0;
}
</style>
</head>
<body>
<main>
<h1>Text Highlighter</h1>
<div>
<p class="smalltitle">Javascript class to highlight search results on a textarea without interfering with its operation</p>
<textarea id="txt" spellcheck="false">
THE EGG
By: Andy Weir
You were on your way home when you died.
It was a car accident. Nothing particularly remarkable, but fatal nonetheless. You left behind a wife and two children. It was a painless death. The EMTs tried their best to save you, but to no avail. Your body was so utterly shattered you were better off, trust me.
And that’s when you met me.
“What… what happened?” You asked. “Where am I?”
“You died,” I said, matter-of-factly. No point in mincing words.
“There was a… a truck and it was skidding…”
“Yup,” I said.
“I… I died?”
“Yup. But don’t feel bad about it. Everyone dies,” I said.
You looked around. There was nothingness. Just you and me. “What is this place?” You asked. “Is this the afterlife?”
“More or less,” I said.
“Are you god?” You asked.
“Yup,” I replied. “I’m God.”
“My kids… my wife,” you said.
“What about them?”
“Will they be all right?”
“That’s what I like to see,” I said. “You just died and your main concern is for your family. That’s good stuff right there.”
You looked at me with fascination. To you, I didn’t look like God. I just looked like some man. Or possibly a woman. Some vague authority figure, maybe. More of a grammar school teacher than the almighty.
“Don’t worry,” I said. “They’ll be fine. Your kids will remember you as perfect in every way. They didn’t have time to grow contempt for you. Your wife will cry on the outside, but will be secretly relieved. To be fair, your marriage was falling apart. If it’s any consolation, she’ll feel very guilty for feeling relieved.”
“Oh,” you said. “So what happens now? Do I go to heaven or hell or something?”
“Neither,” I said. “You’ll be reincarnated.”
“Ah,” you said. “So the Hindus were right,”
“All religions are right in their own way,” I said. “Walk with me.”
You followed along as we strode through the void. “Where are we going?”
“Nowhere in particular,” I said. “It’s just nice to walk while we talk.”
“So what’s the point, then?” You asked. “When I get reborn, I’ll just be a blank slate, right? A baby. So all my experiences and everything I did in this life won’t matter.”
“Not so!” I said. “You have within you all the knowledge and experiences of all your past lives. You just don’t remember them right now.”
I stopped walking and took you by the shoulders. “Your soul is more magnificent, beautiful, and gigantic than you can possibly imagine. A human mind can only contain a tiny fraction of what you are. It’s like sticking your finger in a glass of water to see if it’s hot or cold. You put a tiny part of yourself into the vessel, and when you bring it back out, you’ve gained all the experiences it had.
“You’ve been in a human for the last 48 years, so you haven’t stretched out yet and felt the rest of your immense consciousness. If we hung out here for long enough, you’d start remembering everything. But there’s no point to doing that between each life.”
“How many times have I been reincarnated, then?”
“Oh lots. Lots and lots. An in to lots of different lives.” I said. “This time around, you’ll be a Chinese peasant girl in 540 AD.”
“Wait, what?” You stammered. “You’re sending me back in time?”
“Well, I guess technically. Time, as you know it, only exists in your universe. Things are different where I come from.”
“Where you come from?” You said.
“Oh sure,” I explained “I come from somewhere. Somewhere else. And there are others like me. I know you’ll want to know what it’s like there, but honestly you wouldn’t understand.”
“Oh,” you said, a little let down. “But wait. If I get reincarnated to other places in time, I could have interacted with myself at some point.”
“Sure. Happens all the time. And with both lives only aware of their own lifespan you don’t even know it’s happening.”
“So what’s the point of it all?”
“Seriously?” I asked. “Seriously? You’re asking me for the meaning of life? Isn’t that a little stereotypical?”
“Well it’s a reasonable question,” you persisted.
I looked you in the eye. “The meaning of life, the reason I made this whole universe, is for you to mature.”
“You mean mankind? You want us to mature?”
“No, just you. I made this whole universe for you. With each new life you grow and mature and become a larger and greater intellect.”
“Just me? What about everyone else?”
“There is no one else,” I said. “In this universe, there’s just you and me.”
You stared blankly at me. “But all the people on earth…”
“All you. Different incarnations of you.”
“Wait. I’m everyone!?”
“Now you’re getting it,” I said, with a congratulatory slap on the back.
“I’m every human being who ever lived?”
“Or who will ever live, yes.”
“I’m Abraham Lincoln?”
“And you’re John Wilkes Booth, too,” I added.
“I’m Hitler?” You said, appalled.
“And you’re the millions he killed.”
“I’m Jesus?”
“And you’re everyone who followed him.”
You fell silent.
“Every time you victimized someone,” I said, “you were victimizing yourself. Every act of kindness you’ve done, you’ve done to yourself. Every happy and sad moment ever experienced by any human was, or will be, experienced by you.”
You thought for a long time.
“Why?” You asked me. “Why do all this?”
“Because someday, you will become like me. Because that’s what you are. You’re one of my kind. You’re my child.”
“Whoa,” you said, incredulous. “You mean I’m a god?”
“No. Not yet. You’re a fetus. You’re still growing. Once you’ve lived every human life throughout all time, you will have grown enough to be born.”
“So the whole universe,” you said, “it’s just…”
“An egg.” I answered. “Now it’s time for you to move on to your next life.”
And I sent you on your way.
</textarea>
<p><b>Enter a search term below to start you search!</b>
<ul>
<li>Then choose the case sensitivity of the search and if it'll be free or words only. </li>
<li>Next, click the SEARCH button or hit ENTER to start a search. </li>
<li> If you get any results, you can use the PREV (◀) and NEXT (▶) buttons <i>(that only appear after something is highlighted)</i> to navigate them. </li>
<li>You can also use the resize handler to change the box's dimensions and see the result markings adjust in real time. </li>
<li>Finally, click the CLEAR button to remove any highlighted items and reset the class or just type a new search term and click SEARCH again. </li>
</ul>
</p>
<hr>
<nav>
<span>
<input type="text" id="find" onkeypress="preGo(event)" placeholder="Enter search term" />
<select id="sens">
<option value="">Insensitive</option>
<option value="1">Sensitive</option>
</select>
<select id="word">
<option value="">Free Search</option>
<option value="1">Words Only</option>
</select>
</span>
<span>
<button onclick="markText()">Search</button>
</span>
<span id="hoppers" class="hidden">
<button onclick="move('p')">◀</button>
<button onclick="move('n')">▶</button>
</span>
<span class="clear">
<button onclick="cls()">Clear</button>
</span>
</nav>
<div class="found"><span id="count"></span> Found</div>
<br><br>
</div>
</main>
<script>
let tarea, hilite, find, count, hoppers;
function preGo(evt) {
if (evt.key === "Enter") {
event.preventDefault();
markText();
}
}
function markText() {
let arg = document.getElementById('find').value;
let sens = document.getElementById('sens').value;
let word = document.getElementById('word').value;
if (arg) {
hilite.search(arg, sens, word);
count.textContent = hilite.count();
hopperButtons();
}
}
function cls() {
hilite.clear();
count.textContent = '0';
find.value = '';
hopperButtons();
find.focus();
}
function move(op) {
if (op == 'p') { hilite.prev(); } else { hilite.next(); }
}
function inputHandler() {
count.textContent = hilite.count();
hopperButtons();
}
function hopperButtons() {
+count.textContent ? hoppers.classList.remove('hidden') : hoppers.classList.add('hidden');
}
document.addEventListener('DOMContentLoaded', function() {
tarea = document.getElementById('txt');
find = document.getElementById('find');
count = document.getElementById('count');
hoppers = document.getElementById('hoppers');
hilite = new textHighlight(tarea);
count.textContent = '0';
tarea.addEventListener('input', inputHandler);
inputHandler();
});
</script>
</body>
</html>
================================================
FILE: texthighlighter.css
================================================
.hlta-container {
position: relative;
text-size-adjust: none;
}
.hlta-backdrop {
position: absolute;
overflow: hidden;
border-color: transparent;
}
.hlta-highlight {
color: transparent !important;
word-wrap: break-word !important;
}
.hlta-highlight > * {
display: none;
}
.hlta-container > .hlta-textarea {
position: relative;
background: none transparent !important;
}
.hlta-highlight > mark {
background-color: #fccfc8;
display: inline-block;
}
.hlta-highlight > mark.sel {
background-color: #ff8572;
}
================================================
FILE: texthighlighter.js
================================================
/* *******************************************************
By Walter Staeblein - 2023
MIT Licence - https://choosealicense.com/licenses/mit/
https://github.com/wstaeblein/highlightTextarea
*******************************************************/
class textHighlight {
constructor(ele) {
if (ele.tagName != 'TEXTAREA') { throw 'The element must be a textarea'; }
let styles = window.getComputedStyle(ele);
this.origBkgColor = styles.backgroundColor;
this.ele = ele;
this.searchArg = '';
this.sensitive = false;
this.sel = -1;
this.handlers = {
input: this.#inputHandler.bind(this),
scroll: this.#scrollHandler.bind(this)
}
this.ele.classList.add('hlta-textarea');
this.ele.addEventListener('input', this.handlers.input);
this.ele.addEventListener('scroll', this.handlers.scroll);
let nodeCont = document.createElement('div');
nodeCont.classList.add('hlta-container');
this.container = nodeCont;
let nodeBack = document.createElement('div');
nodeBack.classList.add('hlta-backdrop');
this.backdrop = nodeBack;
let nodeHilite = document.createElement('div');
nodeHilite.classList.add('hlta-highlight');
this.hilite = nodeHilite;
this.ele.parentNode.insertBefore(nodeCont, this.ele.nextSibling);
this.backdrop.append(this.hilite);
this.container.append(this.backdrop);
this.container.appendChild(this.ele);
let observer = new ResizeObserver(this.#resizeObs.bind(this));
observer.observe(this.ele);
this.#inputHandler();
}
search(arg, sensitive, word) {
this.searchArg = arg;
this.sensitive = !!sensitive;
this.word = !!word;
this.#inputHandler();
this.sel = -1;
this.next();
}
next() {
this.sel +=1;
this.#setSelection(true);
}
prev() {
this.sel -=1;
this.#setSelection(true);
}
count() {
let eles = this.hilite.querySelectorAll('mark');
return eles.length;
}
clear() {
this.searchArg = '';
this.hilite.innerHTML = this.hilite.textContent;
this.sel = -1;
}
destroy() {
this.ele.removeEventListener('input', this.handlers.input);
this.ele.removeEventListener('scroll', this.handlers.scroll);
observer.disconnect();
this.container.parentNode.insertBefore(this.ele, this.container);
while (this.container.firstChild) {
this.container.removeChild(this.container.lastChild);
}
this.container.remove();
}
#resizeObs() {
let styles = window.getComputedStyle(this.ele);
let width = this.ele.scrollWidth;
let height = this.ele.offsetHeight;
let css = `width: ${width}px; height: ${height}px; margin: ${styles.marginTop} ${styles.marginRight} ${styles.marginBottom} ${styles.marginLeft};
background-color: ${this.origBkgColor}`;
this.backdrop.style.cssText = css;
this.#copyStyles(this.ele, this.hilite, ['width', 'paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom', 'borderTop', 'letterSpacing',
'borderLeft', 'borderRight', 'borderBottom', 'fontFamily', 'fontSize', 'fontWeight', 'lineHeight']);
this.hilite.style.minHeight = styles.height;
this.hilite.style.whiteSpace = 'pre-wrap';
}
#inputHandler() {
this.hilite.innerHTML = this.#markText();
this.#scrollHandler();
if (this.sel > -1) { this.#setSelection(); }
}
#copyStyles(src, dest, styles2Copy) {
let styles = window.getComputedStyle(src);
styles2Copy.forEach((stl) => dest.style[stl] = styles[stl])
}
#markText() {
let txt = this.ele.value.replace(/</g, '<').replace(/>/g, '>');
if (this.searchArg) { console.log(this.ele.value)
let searchArg = this.searchArg.replace(/</g, '<').replace(/>/g, '>');
let boundary = this.word ? '\\b' : '';
let re = new RegExp(boundary + '(' + this.#escapeString(searchArg) + ')' + boundary, 'g' + (this.sensitive ? '' : 'i'));
return txt.replace(re, '<mark>$&</mark>');
} else {
return txt;
}
}
#escapeString(txt) {
let specials = ['-', '[', ']', '/', '{', '}', '(', ')', '*', '+', '?', '.', '\\', '^', '$', '|'];
return txt.replace(RegExp('[' + specials.join('\\') + ']', 'g'), '\\$&');
}
#scrollHandler() {
this.backdrop.scrollTop = this.ele.scrollTop || 0;
let sclLeft = this.ele.scrollLeft;
this.backdrop.style.transform = (sclLeft > 0) ? 'translateX(' + -sclLeft + 'px)' : '';
}
#setSelection(scroll) {
let eles = this.hilite.querySelectorAll('mark');
let len = eles.length;
if (this.sel >= len) { this.sel = 0; }
if (this.sel < 0) { this.sel = len - 1; }
for (let i = 0; i < len; ++i) {
if (i == this.sel) {
eles[i].classList.add('sel');
if (scroll) { this.ele.scrollTop = eles[i].offsetTop > 10 ? eles[i].offsetTop - 10 : eles[i].offsetTop; }
} else {
eles[i].classList.remove('sel');
}
}
}
}
gitextract_mzocae5i/ ├── LICENSE ├── README.md ├── index.html ├── texthighlighter.css └── texthighlighter.js
SYMBOL INDEX (15 symbols across 1 files)
FILE: texthighlighter.js
class textHighlight (line 7) | class textHighlight {
method constructor (line 8) | constructor(ele) {
method search (line 49) | search(arg, sensitive, word) {
method next (line 58) | next() {
method prev (line 63) | prev() {
method count (line 68) | count() {
method clear (line 73) | clear() {
method destroy (line 79) | destroy() {
method #resizeObs (line 91) | #resizeObs() {
method #inputHandler (line 105) | #inputHandler() {
method #copyStyles (line 111) | #copyStyles(src, dest, styles2Copy) {
method #markText (line 116) | #markText() {
method #escapeString (line 130) | #escapeString(txt) {
method #scrollHandler (line 135) | #scrollHandler() {
method #setSelection (line 141) | #setSelection(scroll) {
Condensed preview — 5 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (25K chars).
[
{
"path": "LICENSE",
"chars": 1073,
"preview": "MIT License\n\nCopyright (c) 2023 Walter Staeblein\n\nPermission is hereby granted, free of charge, to any person obtaining "
},
{
"path": "README.md",
"chars": 3304,
"preview": "# Text Highlighter\n\nVanilla JS class to highlight search results in a textarea while maintaining the area's functionalit"
},
{
"path": "index.html",
"chars": 13632,
"preview": "<!DOCTYPE html>\n<html lang=\"pt\">\n <head>\n <title>Highlight Textarea Component</title>\n <meta charset=\"U"
},
{
"path": "texthighlighter.css",
"chars": 565,
"preview": ".hlta-container {\n position: relative;\n text-size-adjust: none;\n}\n\n.hlta-backdrop {\n position: absolute;\n ov"
},
{
"path": "texthighlighter.js",
"chars": 5462,
"preview": "/* *******************************************************\n By Walter Staeblein - 2023\n MIT Licence - https://cho"
}
]
About this extraction
This page contains the full source code of the wstaeblein/texthighlighter GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 5 files (23.5 KB), approximately 5.6k tokens, and a symbol index with 15 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.