Aariba Aariba - 1 month ago 4
Javascript Question

Find next text by search and highlight not works

When search any text on search box, it can be find and highlighted the correct text, but when search next/new text, it's unable to find the next/new text, it's not working when search again, i'm unable to find the issue. The JS below.


$('button#search').click(function() {
var page = $('#ray-all_text');
var pageText = page.html().replace("<span>", "").replace("</span>");
var searchedText = $('#searchfor').val();
var theRegEx = new RegExp("(" + searchedText + ")", "igm");
var newHtml = pageText.replace(theRegEx, "<span>$1</span>");
$('html, body').animate({
scrollTop: $("#ray-all_text span").offset().top }, 2000);


<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 the live Example: https://jsfiddle.net/gaezs6s8

Why is this happening? Is there a solution?


My suggestion is to make a few validations before change all the .html() inside the text you want to avoid unexpected behaviors and improve the functionality.

First make a validation to avoid the 'space' as the first value on the input, this will let us later check if the input has a real value inside.

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

Code from this answer

Now Please check the comments on your code:

//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')