2 * Plugin that highlights matched word partials in a given element
3 * TODO: add a function for restoring the previous text
4 * TODO: accept mappings for converting shortcuts like WP: to Wikipedia:
10 // Split our pattern string at spaces and run our highlight function on the results
11 splitAndHighlight: function( node
, pat
) {
12 var patArray
= pat
.split(" ");
13 for ( var i
= 0; i
< patArray
.length
; i
++ ) {
14 if ( patArray
[i
].length
== 0 ) continue;
15 $.highlightText
.innerHighlight( node
, patArray
[i
] );
19 // scans a node looking for the pattern and wraps a span around each match
20 innerHighlight: function( node
, pat
) {
21 // if this is a text node
22 if ( node
.nodeType
== 3 ) {
23 // TODO - need to be smarter about the character matching here.
24 // non latin characters can make regex think a new word has begun.
25 // look for an occurence of our pattern and store the starting position
26 var pos
= node
.data
.search( new RegExp( "\\b" + RegExp
.escape( pat
), "i" ) );
28 // create the span wrapper for the matched text
29 var spannode
= document
.createElement( 'span' );
30 spannode
.className
= 'highlight';
31 // shave off the characters preceding the matched text
32 var middlebit
= node
.splitText( pos
);
33 // shave off any unmatched text off the end
34 middlebit
.splitText( pat
.length
);
35 // clone for appending to our span
36 var middleclone
= middlebit
.cloneNode( true );
37 // append the matched text node to the span
38 spannode
.appendChild( middleclone
);
39 // replace the matched node, with our span-wrapped clone of the matched node
40 middlebit
.parentNode
.replaceChild( spannode
, middlebit
);
42 // if this is an element with childnodes, and not a script, style or an element we created
43 } else if ( node
.nodeType
== 1 && node
.childNodes
&& !/(script|style)/i.test( node
.tagName
)
44 && !( node
.tagName
.toLowerCase() == 'span' && node
.className
.match( /\bhighlight/ ) ) ) {
45 for ( var i
= 0; i
< node
.childNodes
.length
; ++i
) {
46 // call the highlight function for each child node
47 $.highlightText
.innerHighlight( node
.childNodes
[i
], pat
);
53 $.fn
.highlightText = function( matchString
) {
54 return $( this ).each( function() {
55 var $this = $( this );
56 $this.data( 'highlightText', { originalText
: $this.text() } );
57 $.highlightText
.splitAndHighlight( this, matchString
);