highlight: JavaScript text higlighting jQuery plugin

Posted 2007-09-15 in JavaScript by Johann.

Text higlighting is part of DynaCloud – where tags/keywords are automatically highlighted once they’re clicked – so I took that code and made it a stand-alone JavaScript text highlighting jQuery plugin.

Demo

Each of the links will highlight the corresponding word.

Remove highlights again.

Usage

Add highlight

Download jquery.highlight-5.js (2 KB) and add it to your page after jQuery. A Closure Compiler compressed version (1 KB) is also available.

Style the highlight class

Create an entry in your style sheet for the highlight class.

.highlight { background-color: yellow }

Highlight terms

Call the highlight function with the text to highlight. To highlight all occurrances of “bla” (case insensitive) in all li elements, use the following code:

$('li').highlight('bla');

Remove highlighting

The highlight can be removed from any element with the removeHighlight function. In this example, all highlights under the element with the ID highlight-plugin are removed.

$('#highlight-plugin').removeHighlight();

Forks and Extensions

Changelog

  • 2014-01-11: Bugfix for character expansion during uppercasing. Thanks Guido Jansen.
  • 2009-02-22: Bugfix for one or two strange problems with IE. Also made API easier to use.
  • 2008-06-04: Bugfix for incorrect DOM normalization. Thanks Georgy.
  • 2007-09-15: Initial release.

26 comments

#1 2008-05-09 by Gonzalo



Simple yet useful ! Thanks.

About the "case-sensitiveness", I found out that plugging .js as is, same code was working differently in IE than FF, I mean insensitive in IE while case sensitive in FF, I solved this with a minor modification in the code, in the highlight FF function I

changed line : pos = node.data.toUpperCase().indexOf(te);
by : pos = node.data.toUpperCase().indexOf(te.toUpperCase());

Thought someone else might find out this useful.

Regards,
Gonzalo

#2 2008-05-09 by Johann

Gonzalo,

thanks for the patch, I did not uppercase te on purpose because toUpperCase() would be called over and over again recursively. Maybe I can come up with something that only uppercases the pattern once.

#3 2008-05-26 by Georgy

Hi,
I have noticed a bug.
When you hilight some word (e.g. "quake") and than trying to hilight a word (e.g. "earthquake") that includes the first word than the search for the second word doesnt work, it hilights nothing.

Thanks,
Georgy

#4 2008-10-26 by Thomas David Baker

Well, I got this far:

http://bluebones.net/searchandmanipulate.js.txt

I made it take an array of strings to manipulate (so you can "highlight" more than one thing) plus a callback that receives the text matched and should return an html element to be inserted into the dom, so you can add links or do other arbitrary things.

I added a case sensitivity param.

I wrote a utility function for the generation of "turn the text into a link" callbacks. It takes a callback itself that generates URLs from the string provided.

I also used Nox's idea and added it to the jQuery fn namespace.

So usage would go something like this:

function urlGenerator(s) {
return "http://example.org/?x=" + s;
}

var callback = jQuery.makeLinkCallback(urlGenerator);
$('p').highlight(['foo', 'bar', 'baz'], false, callback);

Which goes through all the p elements in the document making all occurrences of foo, bar and baz into links to http://example.org/?x=foo (or bar, or baz, as appropriate).

At this point I stopped though because the use case I had in mind grew more ambitious and I realized I wanted to check 15,000 phrases. The performance of which is utterly abysmal, of course, and should almost certainly be done server-side.

I put it up and linked to it here just in case it is useful to anyone. If you need help with it I'm bakert at gmail dot com.

#5 2008-11-10 by Wonderbread

Is it possible to do this with images aswell?
EG;
I hit the word "tree" (it's a linked word, like the ones above)
and I had a picture called tree.jpg & the comment of "tree" on it. Would that work?
If not, how could it/can it?

#6 2008-11-10 by Johann

Wonderbread,

good idea, but not so easy since the current loop does only iterate over text. You can try writing an additional function that searches through all a elements after highlight has been called.

#7 2009-02-25 by Kaspars

Is there a version, that highlights separate words, not just phrases?

#8 2009-02-25 by Johann

Kaspars,

you can highlight single words as well.

#9 2009-02-25 by Kaspars

What I meant was - can I highlight all instances of "car" and all instances of "rent" if I feed "car rent" to the script?
I had trouble adapting the modified version by Thomas David Baker which seemed to be highlighting separate words.
What I need to do is grab some words from the page URL (not in the "?q=search phrase" pattern) and then highlight all instances of those words on the page.
I must admit, that my JavaScript knowledge is a bit limited.

#10 2009-02-25 by Johann

Kaspars,

if your words are always separated by space, something like var words = "bla bla"; $.each(words.split(" "), function(idx, val) { ...highlight(val); })

#11 2009-02-25 by Kaspars

Johann,
Thanks for your help so far! I think I am getting there :) Just one thing. I was calling the highlight plugin like this before (and it worked, highlighting the whole phrase):
jQuery('div.SearchFound').each(function() { jQuery.highlight(this, qs); });

qs is a variable holding my string to highlight. Now I am trying to call it like you suggested, but it doesn highlight any words:
jQuery('div.SearchFound').each(qs.split(" "), function(idx, val) { jQuery.highlight(this, val); });

I'm sure I've messed something up. Could you please help me out here?
I really appreciate your help! Your plugin is exactly what I need if I get it highlighting words! :)

#12 2009-02-28 by Johann

Kaspars,

jQuery.each(qs.split(" "), function(idx, val) { jQuery("div.SearchFound").highlight(val); }); should work. Give it a try.

#13 2009-04-06 by Peter


Would it be possible to adapt this so that a number of related items could be highlighted in one colour and another group in another colour?
link to highlight all verbs in red
Second link to highlight all nouns in green

Text marked up as below:

<span class="verbs">go</span>

<span class="verbs">leave</span>

<span class="nouns">box</span>

<span class="nouns">table</span>

#14 2009-04-06 by Johann

Peter,

yes you can do that with CSS rules, for example by setting .verbs .highlight { background-color: red } .nouns .highlight { background-color: green }.

#15 2009-05-25 by bartaz

I guess what Peter wanted is an ability to run highlight few times to select different words with different classes. It can be quite easily done by adding some options for class name (or even element name), so it will be quite close to idea proposed by bober to 'wrap' highlight into some html.

Currently I'm playing with some JavaScript based spell checker for websites so I modified your code a bit so it fits into my needs.
You can check the code at:
http://github.com/bartaz/sandbox-js/blob/master/jquery.highlight.js

Great work with this plugin! I've learned quite a lot from it.
Thanks

#16 2009-08-23 by alexanderia_lover

I Liked this so much and you can use it to highlight more than one word like this
///////
jQuery.fn.highlight = function(text) {
$(this).each(function() {
$.highlight(this, text.toUpperCase());
});
}
//////
var myString = "foo bar baz" ;
myArray = myString.split(" ");
for(i=0;i<myArray.length;i++)
{
$('td').highlight(myArray[i]);
}

#17 2009-09-28 by olive

Highlight plugin in very nice. Can i have how to setfocus the first highlighted text.

#18 2009-09-28 by Johann

olive,

please try something like $('span.highlight:first').focus().

#19 2009-11-02 by Meehal

Hi Johann,

Is it possible to highlight only whole words e.g. when I highlight the word "view", I don't want the "view" in words like "review" to be highlighted.

#20 2009-11-03 by Johann

Meehal,

simple, add spaces :-)

...highlight([' ', word, ' '].join())

#21 2009-11-20 by JBowkett

Hi,
I found this really useful, so I've updated this to toggle hilighting on and off using the same link, I hope it's not too much of a butchering of your code!  (I'm new to JQuery): 
I've posted the updated code here:
http://pastebin.com/f4de84ba8

Hope it helps someone!

-James

#22 2010-01-11 by Ruchi

Hi,
Is it possible to highlight only particular html elements (eg. li with id=li_1). Thanks. Ruchi.

#23 2010-01-12 by Johann

Ruchi,

of course: $('#li_1').highlight('foo')

#24 2010-01-19 by Brian

Ruchi,
Spaces don't work at end of sentences, or if the word has punctuation attached, as in "This is the final word, I've given it to you."

In javascript regex, one can use \b to specify "word boundary" and it will hilight around punctuation and will not then highlight words within words. Simple case of word 'a' - is in thousands of words!

#25 2010-02-09 by Srikrishna

Hi,

Is it possible to select entire text of selection in a web page rather than a keyword to get highlight?

for example:

$('body').mouseup(function(){var selection = window.getSelection();if(selection=='') return false;
else{$(document).highlight(selection);
}});

this giving error 
pat.toUppercase is no a function

pls help

Thanks

#26 2010-02-10 by Johann

Srikrishna,

what you're looking for is most likely if (!selection) or alternatively if (selection) $(document).highlight(selection).
If pat.toUpperCase is not a function, pat is undefined.

Subscribe

RSS 2.0, Atom or subscribe by Email.

Top Posts

  1. DynaCloud - a dynamic JavaScript tag/keyword cloud with jQuery
  2. 6 fast jQuery Tips: More basic Snippets
  3. xslt.js version 3.2 released
  4. xslt.js version 3.0 released XML XSLT now with jQuery plugin
  5. Forum Scanners - prevent forum abuse
  6. Automate JavaScript compression with YUI Compressor and /packer/

Navigation