summaryrefslogtreecommitdiff
path: root/resources/jquery/jquery.highlightText.js
blob: 44ac56e145066a55683cec37c6a82b46b656cf27 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
 * Plugin that highlights matched word partials in a given element
 * TODO: add a function for restoring the previous text
 * TODO: accept mappings for converting shortcuts like WP: to Wikipedia: 
 */
( function( $ ) {

$.highlightText = {
	
	// Split our pattern string at spaces and run our highlight function on the results
	splitAndHighlight: function( node, pat ) {
		var patArray = pat.split(" ");
		for ( var i = 0; i < patArray.length; i++ ) {
			if ( patArray[i].length == 0 ) continue;
			$.highlightText.innerHighlight( node, patArray[i] );
		}
		return node;
	},
	// scans a node looking for the pattern and wraps a span around each match 
	innerHighlight: function( node, pat ) {
		// if this is a text node
		if ( node.nodeType == 3 ) {
			// TODO - need to be smarter about the character matching here. 
			// non latin characters can make regex think a new word has begun: do not use \b
			// http://stackoverflow.com/questions/3787072/regex-wordwrap-with-utf8-characters-in-js
			// look for an occurence of our pattern and store the starting position
			var match = node.data.match( new RegExp( "(^|\\s)" + $.escapeRE( pat ), "i" ) );
			if ( match ) {
				var pos = match.index + match[1].length; // include length of any matched spaces
				// create the span wrapper for the matched text
				var spannode = document.createElement( 'span' );
				spannode.className = 'highlight';
				// shave off the characters preceding the matched text
				var middlebit = node.splitText( pos );
				// shave off any unmatched text off the end
				middlebit.splitText( pat.length );
				// clone for appending to our span
				var middleclone = middlebit.cloneNode( true );
				// append the matched text node to the span
				spannode.appendChild( middleclone );
				// replace the matched node, with our span-wrapped clone of the matched node
				middlebit.parentNode.replaceChild( spannode, middlebit );
			}
		// if this is an element with childnodes, and not a script, style or an element we created
		} else if ( node.nodeType == 1 && node.childNodes && !/(script|style)/i.test( node.tagName )
				&& !( node.tagName.toLowerCase() == 'span' && node.className.match( /\bhighlight/ ) ) ) {
			for ( var i = 0; i < node.childNodes.length; ++i ) {
				// call the highlight function for each child node
				$.highlightText.innerHighlight( node.childNodes[i], pat );
			}
		}
	}
};

$.fn.highlightText = function( matchString ) {
	return $( this ).each( function() {
		var $this = $( this );
		$this.data( 'highlightText', { originalText: $this.text() } );
		$.highlightText.splitAndHighlight( this, matchString );
	} );
};

} )( jQuery );