Skip to content Skip to sidebar Skip to footer

How To Highlight Different Search Results With Mark.js?

My goal I have a text in a HTML page, and I want to be able to use two different search boxes on it, using mark.js. The first search box should highlight matching words in a color,

Solution 1:

My previous answer was for two boxes and one input, but this answer is one box and two inputs, as you requires. I don't remove the previous answer if someone needs that solution

This new solution requires a classname, I called .secondary. See the code:

https://jsfiddle.net/1at87fnu/55/

$(function() {
  var mark = function() {
    // Read the keywordvar keyword = $("input[name='keyword']").val();
    var keyword2 = $("input[name='keyword2']").val();
    // Remove previous marked elements and mark// the new keyword inside the context
    $(".context").unmark({
      done: function() {
        $(".context").mark(keyword).mark(keyword2, {className: 'secondary'});
      }
    });
  };
  $("input[name^='keyword']").on("input", mark);
});

And the CSS

mark {
  padding: 0;
  background-color:yellow;
}
mark.secondary {
  padding: 0;
  background-color: orange;
}

You can see on the javascript that I called twice to mark() function, and on the second call I add a className. You can see more options for mark.js here:

https://markjs.io/#mark

This is a screenshot with the final result:

two inputs and one box

Solution 2:

Just add it on your selector:

https://jsfiddle.net/1at87fnu/49/

  $(function() {
    var mark = function() {
      // Read the keywordvar keyword = $("input[name='keyword']").val();
      // Remove previous marked elements and mark// the new keyword inside the context
      $(".context, .context2").unmark({
        done: function() {
          $(".context, .context2").mark(keyword);
        }
      });
    };
    $("input[name='keyword']").on("input", mark);
  });

html

<inputtype="text"name="keyword"><divclass="context">
    The fox went over the fence
</div><divclass="context2">
    The fox went over the fence
</div>

Thanks to jQuery recursive selectors, you can add all selectors you want by comma separated:

$('.one, #two, three[disabled]')

And so on.

UPDATE

With CSS you can apply different colors between boxes. Just target the box you are using, like this CSS:

https://jsfiddle.net/1at87fnu/50/

mark {
  padding: 0;
  background-color:yellow;
}
.context2mark {
  padding: 0;
  background-color: orange;
}

Post a Comment for "How To Highlight Different Search Results With Mark.js?"