Aariba Aariba - 1 year ago 71
jQuery Question

Find text by search and highlight current result only

Trying to highlight current/single text only, like browser "Control-F" keyboard command search. find next/new text when search again is good. But it's highlight all result, trying to highlight only Current result/text.

JS below:

$('body').on('keydown', '#searchfor', function(e) {
if (e.which === 32 && e.target.selectionStart === 0) {
return false;

//Create some vars to later check for:
//['text you are searching', 'number of highlights','actual highlight']
var searching,

$('button#search').click(function() {
var searchedText = $('#searchfor').val();
var page = $('#ray-all_text');

//Now check if the text on input is valid
if (searchedText != "") {
//If the actual text on the input is different from the prev search
if(searching != searchedText) {
var pageText = page.html();
var theRegEx = new RegExp("(" + searchedText + ")", "igm");
var newHtml = pageText.replace(theRegEx, "<span>$1</span>");
//Set your variables to the actual search
searching = searchedText;
limitsearch = page.find('span').length;
} else {
//If it's the same of the prev search then move to next item instead of repaint html
countsearch<limitsearch-1 ? countsearch++ : countsearch=0;
//Go to target search
scrollTop: $("#ray-all_text span").eq(countsearch).offset().top - 50},
} else {
alert('empty search')


<div class="ray-search">
<div class="field" id="ray-search-form">
<input type="text" id="searchfor" placeholder="what are you searching for?" />
<button type="button" id="search">Press to Find!</button>

<article id="ray-all_text">
This manual and web site, all information and data and photos contained herein, are the s...

Please check example: :https://jsfiddle.net/gaezs6s8/3/

There any solution?

Answer Source

You can add a class to the current target. The lines from your code I change:

var actual = $("#ray-all_text span").eq(countsearch);
   scrollTop: actual.offset().top - 50}, 

And on the CSS:

#ray-all_text span.active {

Demo Fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download