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. ![Screenshot](screen.png) #### [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 ================================================ Highlight Textarea Component

Text Highlighter

Javascript class to highlight search results on a textarea without interfering with its operation

Enter a search term below to start you search!


Found


================================================ 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, '>'); if (this.searchArg) { console.log(this.ele.value) let searchArg = this.searchArg.replace(//g, '>'); let boundary = this.word ? '\\b' : ''; let re = new RegExp(boundary + '(' + this.#escapeString(searchArg) + ')' + boundary, 'g' + (this.sensitive ? '' : 'i')); return txt.replace(re, '$&'); } 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'); } } } }