Added Readme.md
[porter2stemmer.git] / doc / js / quicksearch.js
1 /**
2 *
3 * JQuery QuickSearch - Hook up a form field to hide non-matching elements.
4 * $Id: quicksearch.js 53 2009-01-07 02:52:03Z deveiant $
5 *
6 * Author: Michael Granger <mgranger@laika.com>
7 *
8 */
9 jQuery.fn.quicksearch = function( target, searchElems, options ) {
10 // console.debug( "Quicksearch fn" );
11
12 var settings = {
13 delay: 250,
14 clearButton: false,
15 highlightMatches: false,
16 focusOnLoad: false,
17 noSearchResultsIndicator: null
18 };
19 if ( options ) $.extend( settings, options );
20
21 return jQuery(this).each( function() {
22 // console.debug( "Creating a new quicksearch on %o for %o", this, searchElems );
23 new jQuery.quicksearch( this, searchElems, settings );
24 });
25 };
26
27
28 jQuery.quicksearch = function( searchBox, searchElems, settings ) {
29 var timeout;
30 var boxdiv = $(searchBox).parents('div').eq(0);
31
32 function init() {
33 setupKeyEventHandlers();
34 focusOnLoad();
35 };
36
37 function setupKeyEventHandlers() {
38 // console.debug( "Hooking up the 'keypress' event to %o", searchBox );
39 $(searchBox).
40 unbind( 'keyup' ).
41 keyup( function(e) { return onSearchKey( e.keyCode ); });
42 $(searchBox).
43 unbind( 'keypress' ).
44 keypress( function(e) {
45 switch( e.which ) {
46 // Execute the search on Enter, Tab, or Newline
47 case 9:
48 case 13:
49 case 10:
50 clearTimeout( timeout );
51 e.preventDefault();
52 doQuickSearch();
53 break;
54
55 // Allow backspace
56 case 8:
57 return true;
58 break;
59
60 // Only allow valid search characters
61 default:
62 return validQSChar( e.charCode );
63 }
64 });
65 };
66
67 function focusOnLoad() {
68 if ( !settings.focusOnLoad ) return false;
69 $(searchBox).focus();
70 };
71
72 function onSearchKey ( code ) {
73 clearTimeout( timeout );
74 // console.debug( "...scheduling search." );
75 timeout = setTimeout( doQuickSearch, settings.delay );
76 };
77
78 function validQSChar( code ) {
79 var c = String.fromCharCode( code );
80 return (
81 (c == ':') ||
82 (c >= 'a' && c <= 'z') ||
83 (c >= 'A' && c <= 'Z')
84 );
85 };
86
87 function doQuickSearch() {
88 var searchText = searchBox.value;
89 var pat = new RegExp( searchText, "im" );
90 var shownCount = 0;
91
92 if ( settings.noSearchResultsIndicator ) {
93 $('#' + settings.noSearchResultsIndicator).hide();
94 }
95
96 // All elements start out hidden
97 $(searchElems).each( function(index) {
98 var str = $(this).text();
99
100 if ( pat.test(str) ) {
101 shownCount += 1;
102 $(this).fadeIn();
103 } else {
104 $(this).hide();
105 }
106 });
107
108 if ( shownCount == 0 && settings.noSearchResultsIndicator ) {
109 $('#' + settings.noSearchResultsIndicator).slideDown();
110 }
111 };
112
113 init();
114 };