JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<input type="text" id="search-term" />
<input type="submit" id="search-button" value="search" />
<div id="bodyContainer">
<p class="emptyBlock1000">Empty Space to test Scrolling functionality</p>
<p>Welcome to my search and highlight script</p>
<p>By Tom Alexander</p>
<p>Searching for terms can be done by using the browser's control (or cmd)
+ F feature.</p>
<p>The problem is that not many people know about it and therefore its usefulness
goes out the window</p>
<p>Using this script, we can mimic that functionality by using a search box
and button</p>
<p>More text
<p class="emptyBlock2000">Empty Space to test Scrolling functionality</p>
</div>
CSS
.highlighted {
background-color:yellow;
}
.emptyBlock1000 {
height:1000px;
}
.emptyBlock2000 {
height:2000px;
}
JavaScript
function searchAndHighlight(searchTerm, selector) {
if(searchTerm) {
//var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
//var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
var
match_list,
selector = selector || "body",
searchRegex = new RegExp('(\\W|^)(' + searchTerm + ')(\\W|$)','ig'),
replaceRegex = new RegExp( searchTerm, 'ig' );
var matches = $( selector ).text().match( searchRegex );
if ( matches ) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
$(selector).html($(selector).html()
.replace( replaceRegex, '<span class="highlighted">'+searchTerm + '</span>' ));
if($('.highlighted:first').length) { //if match found, scroll to where the first one appears
$(window).scrollTop($('.highlighted:first').position().top);
}
return true;
}
}
return false;
}
$(document).ready(function() {
$('#search-button').on("click",function() {
if(!searchAndHighlight($('#search-term').val())) {
alert("No results found");
}
});
});