jQuery.info
Découvrir et utiliser jQuery, la librairie javascript du XXIIème siècle

Home page > Plugins > The plugin "SearchHighlight"

The plugin "SearchHighlight"

Tuesday 22 May 2007, by Renato

All the versions of this article: [English] [français] [italiano]

This plugin formats a search results page to highlight the matched keywords.


Demo

a demo page to test all the main configuration options of the plugin.

The idea

Highlighting the matched words on a search results page is not a new idea. It is not always obvious where the keywords are in the page, especially if the page is long with a complex structure. Often the page topic does not match the user’s intended search.

By highlighting the matched keywords, the user can quickly scan and find the relevant parts for his query.

How it works

It’s easy. The key is the unique SearchHighlight(options) function. With this and a few CSS classes to define the highlight you will be up and running in 5 minutes.

The CSS

<style type='text/css'>
 span.hilite {background:yellow}
</style>

The JS

<script src='SearchHighlight.js'></script>
<script type='text/javascript'>
  var opzioni = {exact:"whole",style_name_suffix:false};
  jQuery(function(){
    jQuery(document).SearchHighlight(options);
  });
</script>

SearchHighlight detects the search engine you are coming from and extracts the keywords you are searching for from the URL. Then it finds those words in the page and adds your hilite class around them. Additionally, You can explicitly set the words to be searched, in which case the plugin will not make any test on the URL [1].

Configuration options

The plugin is completely configurable thanks to a number of options:

  • exact (string, default value:"exact")
    "exact" : finds and highlights the words exactly matching those searched
    "whole" : finds partial matches of the words but wholly highlights them
    "partial": finds and highlights partial matches of the words
  • style_name (string, default value:"hilite")
    The class of the span element that wraps the words to be highlighted.
  • style_name_suffix (boolean, default value:true)
    True indicates that each style will be incremented with a number. (hilite1, highlite2, hilite3...) This is useful to find specific matches and style them differently.
  • debug_referrer(string, default value:null)
    Manually sets a referrer for debug purposes.
  • engines (array of regular expressions, default value:null)
    Adds regular expressions to detect more search engines.
    The first array item is the regular expression that matches the domain.
    The second array item is the regular expression that matches the parameter containing the words to be searched for (query string)
    Ex: [/^http:\/\/my\.site\.net/i,/search=([^&]+)/i] allows to detect the domain http://my.site.net as a search engine and extracts the words to be searched for from the search parameter.
    http://my.site.net?search=searched_words
  • highlight (jQuery selector or object, default value:null)
    Use this option to limit the Highlighting to a specific area of the page. Null is the entire document. If no elements are found the plugin consider the entire document as well.
  • nohighlight (jQuery selector or object, default value:null)
    Use this option to exclude the Highlighting from a specific area of the page. It has priority on the highlight option.
  • keys (string, default value:null)
    Allows to explicitly set the words to be searched for, while disabling all the tests against the referrer. Useful to disable search engines highlight and to highlight words extracted from page url or from the DOM.

P.S.

Thanks to Glen Lipka for his help with the English translation and its ideas to make a better plugin.

Attached documents

Footnotes

[1] the referrer is the url of the page you are coming from

Reply to this article

16 Forum messages

  • (logo)

    incompatible avec dernière version ?

    29 October 2006 16:16, by spif

    Cet exemple fonctionne tant qu’on charge la librairie à partir de l’url http://jquery.com/src/latest/. En chargeant jquery-1.0.3.js en local, j’obtiens "Erreur : $("a").set is not a function". Problème de version ?

    Reply to this message

  • (logo)

    The plugin "SearchHighlight"

    2 July 2008 18:19

    You may want to change the plugin code in order to avoid Internet Explorer Bug Warnings (yellow sign in the bottom left of the browser):

    From

    $.each(reg,function(i,n)
    if(n[0].test(URL))
    var match = URL.match(n[1]);
    if(match)
    query = match[1].toLowerCase();
    return false;


    )

    to

    $.each(reg,function(i,n)
    if(typeof n == ’object’)
    if(n[0].test(URL))
    var match = URL.match(n[1]);
    if(match)
    query = match[1].toLowerCase();
    return false;



    )

    Reply to this message

  • (logo)

    The plugin "SearchHighlight"

    19 December 2008 09:34, by Jammi

    Amazing plugin, thanks a lot for sharing this.

    Reply to this message

    • (logo)
      The plugin "SearchHighlight" 15 December 2009 10:10

      I m using jQuery plugin "jquery-1.3.2.min.js" in my solution for popup window. If I am inculding this plugin in my solution then glossary tooltip working fine in IE browser but it is not working in other browser. But if I exclude "jquery-1.3.2.min.js" then tooltip is working in Safari, Firefox and IE.

      also if a term has two words or special character then this solution is not working.

      Please suggest how to resolve the issue.

      Thanks
      Furqan

      Reply to this message

      • (logo)
        The plugin "SearchHighlight" 15 December 2009 12:45, by Isaac

        Hello,
        I did some changes in the plugin ...see all code :
        /*
        highlight v3

        Highlights arbitrary terms.
        /johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
        MIT license.

        Johann Burkard /johannburkard.de> <mailto:jb@eaio.com>
        Isaac flores <florespaz_isaac@hotmail.com> Added glossary feature
        Julio Montoya <gugli100@gmail.com> fixes for the Glossary tool to strict search

        */

        jQuery.fn.highlight = function(pat,real_code)
        function innerHighlight(node, pat)
        var skip = 0;
        if (node.nodeType == 3 )
        // Highlight all coincidences
        //var pos = node.data.toUpperCase().indexOf(pat);
        //Highlight strict, exact words
        var SearchRegExp = new RegExp("(\\b)"+pat+"(\\b)","gi");
        var pos = node.nodeValue.search(SearchRegExp);
        if (pos >= 0 )
        var spannode = document.createElement(’a’);
        spannode.className = ’glossary-ajax’;
        spannode.style.color = ’#084B8A’;
        spannode.style.fontWeight=’100’;
        spannode.style.textDecoration = ’none’;
        spannode.name = ’link’+real_code;
        spannode.href = ’#’;
        var SearchRegExp = new RegExp("(" + pat +")","gi");
        var MatchRegExp = node.nodeValue.match(SearchRegExp);
        if (MatchRegExp == null)
        MatchRegExp = new Array();

        if (MatchRegExp.length > 0 && node.nodeValue[pat.length+1] != ’’)
        var middlebit = node.splitText(pos);
        var endbit = middlebit.splitText(pat.length);
        if (endbit.nodeValue[0] == null || endbit.nodeValue[0] == ’ ’ || endbit.nodeValue[0] == ’.’ || endbit.nodeValue[0] == ’,’ || endbit.nodeValue[0] == ’;’ || endbit.nodeValue[0] == ’"’)
        var middleclone = middlebit.cloneNode(true);
        spannode.appendChild(middleclone);
        middlebit.parentNode.replaceChild(spannode, middlebit);


        skip = 1;

        else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName))
        for (var i = 0; i
        i += innerHighlight(node.childNodes[i], pat);


        return skip;

        return this.each(function()
        innerHighlight(this, pat.toUpperCase());
        ); ;

        jQuery.fn.removeHighlight = function()
        return this.find("a.highlight").each(function()
        this.parentNode.firstChild.nodeName;
        with (this.parentNode)
        replaceChild(this.firstChild, this);
        normalize();

        ).end();

        ;

        See online : About the plugin "SearchHighlight"

        Reply to this message

  • (logo)

    The plugin "SearchHighlight"

    17 December 2009 14:07, by Kevin

    A fellow developer friend passed me version 0.36 (9/1/2009) but version 0.33 is only available for download. Is 0.36 available for download in packed and unpacked version? Is 0.36 a stable version?

    Reply to this message

  • (logo)

    The plugin "SearchHighlight"

    20 December 2009 15:53

    There is a problem with some language like Persian and Arabic.
    The query for this languages are like this :

    http://......./?q=%DA%A9%D9%85%D9%BE%D8%B1%D8%B3

    instead of this :

    http://......../?q=کمپرس

    So this script not work in this case.

    See online : http://cyberrabbits.net

    Reply to this message

  • (logo)

    The plugin "SearchHighlight"

    31 March 2010 21:34, by Jake

    Nice plugin- thanks for putting it together. If anyone needs a simple highlighting function, you can use...

    jQuery.fn.highlight = function (str, className) var regex = new RegExp(str, "g"); return this.each(function () this.innerHTML = this.innerHTML.replace(regex, "" + str + ""); ); ;
    $(function()
    $("li").highlight("how","highlight");
    $("li").highlight("today","highlight");
    );

    //CSS
    .highlight background-color: yellow

    Reply to this message

  • (logo)

    The plugin "SearchHighlight" question

    21 May 2010 12:03, by lienquan

    I searched for Vietnamese, this script does not properly.
    Examplale:


    jQuery(function()

    var options =

    exact:"partial",

    style_name_suffix:false,

    highlight:".highlightable",

    keys:"chinh la mot thu vien kieu"

    jQuery(document).SearchHighlight(options);

    );


    JQuery chính là một thư viện kiểu mới của Javascript giúp đơn giản hóa cách viết Javascript và tăng tốc độ xử lý các sự kiện trên trang web.

    >

    only highlight "chính" and "là" , but "thư viện kiểu" is not highlight
    Result:
    JQuery chính là một thư viện kiểu mới của Javascript giúp đơn giản hóa cách viết Javascript và tăng tốc độ xử lý các sự kiện trên trang web.

    See online : The plugin "SearchHighlight" question

    Reply to this message

  • (logo)

    The plugin "SearchHighlight"

    5 January 2011 15:57

    I cant get it to work, It will highlight the specific word. but when the textbox changes the highlight wont change.

    code:

    $(document).ready(function ()
    $("input[name=’search’]").keyup(function()
    $("table").SearchHighlight( exact:"partial", keys:$("input[name=’search’]").val() );
    );
    );

    I need to highlight text (in table) on input change

    Reply to this message

  • (logo)

    The plugin "SearchHighlight"

    15 April 2011 17:39, by deadelvis

    FIY ... latest version (0.37 as per this message) seems to be kept here:
    http://trac.spip.org/browser/prive/...

    Reply to this message

  • (logo)

    Dans SPIP avec un CVT ajaxé ?

    27 May 2011 13:21

    Hello,

    Dans SPIP avec un CVT qui fait office de formulaire de recherche, je cherche à surligner les résultats qui correspondent à la recherche.

    C’est possible, mais dans ce cas on ne peut pas ajaxer le formulaire :
    Tout d’abord le code d’appel à highlight n’est pas inclus.
    D’autre part, si on le fait inclure d’office, la 2ème page de résultat n’est pas traitée.
    J’ai essayé de modifier le javascript qui déclenche le jquery mais je n’y suis pas arrivé.
    Y aurait-il une autre méthode d’appel que

    if (window.jQuery)

    qui permettrait d’attaquer le bout de html qui vient de se recharger par ajax ?

    Merci pour vos lumières,

    Gerald

    Reply to this message


Latest comments