Highlight text with jQuery

Here I am going to show how to highlight particular word within a block of text.
You can use this feature to:
– highlight the search terms on the page.
– highlight particular keywords dynamically on the page.
– highlight negative numeric values on block of page.

Below is the working example, enter the text in textbox and click on “highlight” button to highlight the text in the block.

Sample text for highlight.

Sample text for highlight1.

Let us take a the sample text

 language="html"]

Sample text for highlight.

Sample text for highlight1.

$(document).ready(function() { $('input[name="hbtn"]').click(function() { var o ={words:$('input[name="query"]').val()}; highlight("content-block", o); }); });

here is the code for highlight the word in block of text

 language="js"]
function highlight(id, options) {
  var o = {
    words: '',
    caseSensitive: false,
    wordsOnly: true,
    template: '$1$2$3'
  }, pattern;
  $.extend(true, o, options || {});

  if (o.words.length == 0) { return; }
  pattern = new RegExp('(>[^<.]*)(' + o.words + ')([^<.]*)', o.caseSensitive ? "" : "ig");

  $('#'+id).each(function() {
    var content = $(this).html();
    if (!content) return;
    $(this).html(content.replace(pattern, o.template));
    });
  }


Comments

  1. By andy

    Reply

  2. By andy

    Reply

    • By admin

      Reply

  3. By andy

    Reply

  4. By el

    Reply

  5. By e

    Reply

  6. By el

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami