9fc8a47d9c4f5dace1373c153d9160059eaef38c
2 * This plugin provides a generic way to add suggestions to a text box.
7 * $('#textbox').suggestions( { option1: value1, option2: value2 } );
8 * $('#textbox').suggestions( option, value );
10 * value = $('#textbox').suggestions( option );
12 * $('#textbox').suggestions();
16 * fetch(query): Callback that should fetch suggestions and set the suggestions property. Executed in the context of the
19 * cancel: Callback function to call when any pending asynchronous suggestions fetches should be canceled.
20 * Executed in the context of the textbox
22 * special: Set of callbacks for rendering and selecting
23 * Type: Object of Functions 'render' and 'select'
24 * result: Set of callbacks for rendering and selecting
25 * Type: Object of Functions 'render' and 'select'
26 * $region: jQuery selection of element to place the suggestions below and match width of
27 * Type: jQuery Object, Default: $(this)
28 * suggestions: Suggestions to display
29 * Type: Array of strings
30 * maxRows: Maximum number of suggestions to display at one time
31 * Type: Number, Range: 1 - 100, Default: 7
32 * delay: Number of ms to wait for the user to stop typing
33 * Type: Number, Range: 0 - 1200, Default: 120
34 * submitOnClick: Whether to submit the form containing the textbox when a suggestion is clicked
35 * Type: Boolean, Default: false
36 * maxExpandFactor: Maximum suggestions box width relative to the textbox width. If set to e.g. 2, the suggestions box
37 * will never be grown beyond 2 times the width of the textbox.
38 * Type: Number, Range: 1 - infinity, Default: 3
39 * positionFromLeft: Whether to position the suggestion box with the left attribute or the right
40 * Type: Boolean, Default: true
41 * highlightInput: Whether to hightlight matched portions of the input or not
42 * Type: Boolean, Default: false
48 * Cancel any delayed updateSuggestions() call and inform the user so
49 * they can cancel their result fetching if they use AJAX or something
51 cancel: function( context
) {
52 if ( context
.data
.timerID
!= null ) {
53 clearTimeout( context
.data
.timerID
);
55 if ( typeof context
.config
.cancel
== 'function' ) {
56 context
.config
.cancel
.call( context
.data
.$textbox
);
60 * Restore the text the user originally typed in the textbox, before it was overwritten by highlight(). This
61 * restores the value the currently displayed suggestions are based on, rather than the value just before
62 * highlight() overwrote it; the former is arguably slightly more sensible.
64 restore: function( context
) {
65 context
.data
.$textbox
.val( context
.data
.prevText
);
68 * Ask the user-specified callback for new suggestions. Any previous delayed call to this function still pending
69 * will be canceled. If the value in the textbox hasn't changed since the last time suggestions were fetched, this
70 * function does nothing.
71 * @param {Boolean} delayed Whether or not to delay this by the currently configured amount of time
73 update: function( context
, delayed
) {
74 // Only fetch if the value in the textbox changed
75 function maybeFetch() {
76 if ( context
.data
.$textbox
.val() !== context
.data
.prevText
) {
77 context
.data
.prevText
= context
.data
.$textbox
.val();
78 if ( typeof context
.config
.fetch
== 'function' ) {
79 context
.config
.fetch
.call( context
.data
.$textbox
, context
.data
.$textbox
.val() );
83 // Cancel previous call
84 if ( context
.data
.timerID
!= null ) {
85 clearTimeout( context
.data
.timerID
);
88 // Start a new asynchronous call
89 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
93 $.suggestions
.special( context
);
95 special: function( context
) {
96 // Allow custom rendering - but otherwise don't do any rendering
97 if ( typeof context
.config
.special
.render
== 'function' ) {
98 // Wait for the browser to update the value
99 setTimeout( function() {
101 $special
= context
.data
.$container
.find( '.suggestions-special' );
102 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val() );
107 * Sets the value of a property, and updates the widget accordingly
108 * @param property String Name of property
109 * @param value Mixed Value to set property with
111 configure: function( context
, property
, value
) {
112 // Validate creation using fallback values
119 context
.config
[property
] = value
;
122 context
.config
[property
] = value
;
123 // Update suggestions
124 if ( typeof context
.data
!== 'undefined' ) {
125 if ( context
.data
.$textbox
.val().length
== 0 ) {
126 // Hide the div when no suggestion exist
127 context
.data
.$container
.hide();
129 // Rebuild the suggestions list
130 context
.data
.$container
.show();
131 // Update the size and position of the list
133 'top': context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
135 'width': context
.config
.$region
.outerWidth(),
138 if ( context
.config
.positionFromLeft
) {
139 newCSS
['left'] = context
.config
.$region
.offset().left
;
140 newCSS
['right'] = 'auto';
142 newCSS
['left'] = 'auto';
143 newCSS
['right'] = $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
145 context
.data
.$container
.css( newCSS
);
146 var $results
= context
.data
.$container
.children( '.suggestions-results' );
149 var $autoEllipseMe
= $( [] );
150 var matchedText
= null;
151 for ( var i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
152 var text
= context
.config
.suggestions
[i
];
153 var $result
= $( '<div />' )
154 .addClass( 'suggestions-result' )
156 .data( 'text', context
.config
.suggestions
[i
] )
157 .mousemove( function( e
) {
158 context
.data
.selectedWithMouse
= true;
159 $.suggestions
.highlight(
160 context
, $(this).closest( '.suggestions-results div' ), false
163 .appendTo( $results
);
164 // Allow custom rendering
165 if ( typeof context
.config
.result
.render
== 'function' ) {
166 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[i
] );
168 // Add <span> with text
169 if( context
.config
.highlightInput
) {
170 matchedText
= context
.data
.prevText
;
172 $result
.append( $( '<span />' )
173 .css( 'whiteSpace', 'nowrap' )
177 // Widen results box if needed
178 // New width is only calculated here, applied later
179 var $span
= $result
.children( 'span' );
180 if ( $span
.outerWidth() > $result
.width() && $span
.outerWidth() > expWidth
) {
181 // factor in any padding, margin, or border space on the parent
182 expWidth
= $span
.outerWidth() + ( context
.data
.$container
.width() - $span
.parent().width());
184 $autoEllipseMe
= $autoEllipseMe
.add( $result
);
187 // Apply new width for results box, if any
188 if ( expWidth
> context
.data
.$container
.width() ) {
189 var maxWidth
= context
.config
.maxExpandFactor
*context
.data
.$textbox
.width();
190 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
192 // autoEllipse the results. Has to be done after changing the width
193 $autoEllipseMe
.autoEllipsis( { hasSpan
: true, tooltip
: true, matchText
: matchedText
} );
198 context
.config
[property
] = Math
.max( 1, Math
.min( 100, value
) );
201 context
.config
[property
] = Math
.max( 0, Math
.min( 1200, value
) );
203 case 'maxExpandFactor':
204 context
.config
[property
] = Math
.max( 1, value
);
206 case 'submitOnClick':
207 case 'positionFromLeft':
208 case 'highlightInput':
209 context
.config
[property
] = value
? true : false;
214 * Highlight a result in the results table
215 * @param result <tr> to highlight: jQuery object, or 'prev' or 'next'
216 * @param updateTextbox If true, put the suggestion in the textbox
218 highlight: function( context
, result
, updateTextbox
) {
219 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
220 if ( !result
.get || selected
.get( 0 ) != result
.get( 0 ) ) {
221 if ( result
== 'prev' ) {
222 if( selected
.is( '.suggestions-special' ) ) {
223 result
= context
.data
.$container
.find( '.suggestions-result:last' )
225 result
= selected
.prev();
226 if ( selected
.length
== 0 ) {
227 // we are at the begginning, so lets jump to the last item
228 if ( context
.data
.$container
.find( '.suggestions-special' ).html() != "" ) {
229 result
= context
.data
.$container
.find( '.suggestions-special' );
231 result
= context
.data
.$container
.find( '.suggestions-results div:last' );
235 } else if ( result
== 'next' ) {
236 if ( selected
.length
== 0 ) {
237 // No item selected, go to the first one
238 result
= context
.data
.$container
.find( '.suggestions-results div:first' );
239 if ( result
.length
== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() != "" ) {
240 // No suggestion exists, go to the special one directly
241 result
= context
.data
.$container
.find( '.suggestions-special' );
244 result
= selected
.next();
245 if ( selected
.is( '.suggestions-special' ) ) {
248 result
.length
== 0 &&
249 context
.data
.$container
.find( '.suggestions-special' ).html() != ""
251 // We were at the last item, jump to the specials!
252 result
= context
.data
.$container
.find( '.suggestions-special' );
256 selected
.removeClass( 'suggestions-result-current' );
257 result
.addClass( 'suggestions-result-current' );
259 if ( updateTextbox
) {
260 if ( result
.length
== 0 || result
.is( '.suggestions-special' ) ) {
261 $.suggestions
.restore( context
);
263 context
.data
.$textbox
.val( result
.data( 'text' ) );
264 // .val() doesn't call any event handlers, so
265 // let the world know what happened
266 context
.data
.$textbox
.change();
268 context
.data
.$textbox
.trigger( 'change' );
272 * Respond to keypress event
273 * @param key Integer Code of key pressed
275 keypress: function( e
, context
, key
) {
276 var wasVisible
= context
.data
.$container
.is( ':visible' );
277 var preventDefault
= false;
282 $.suggestions
.highlight( context
, 'next', true );
283 context
.data
.selectedWithMouse
= false;
285 $.suggestions
.update( context
, false );
287 preventDefault
= true;
292 $.suggestions
.highlight( context
, 'prev', true );
293 context
.data
.selectedWithMouse
= false;
295 preventDefault
= wasVisible
;
299 context
.data
.$container
.hide();
300 $.suggestions
.restore( context
);
301 $.suggestions
.cancel( context
);
302 context
.data
.$textbox
.trigger( 'change' );
303 preventDefault
= wasVisible
;
307 context
.data
.$container
.hide();
308 preventDefault
= wasVisible
;
309 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
310 if ( selected
.size() == 0 || context
.data
.selectedWithMouse
) {
311 // if nothing is selected OR if something was selected with the mouse,
312 // cancel any current requests and submit the form
313 $.suggestions
.cancel( context
);
314 context
.config
.$region
.closest( 'form' ).submit();
315 } else if ( selected
.is( '.suggestions-special' ) ) {
316 if ( typeof context
.config
.special
.select
== 'function' ) {
317 context
.config
.special
.select
.call( selected
, context
.data
.$textbox
);
320 if ( typeof context
.config
.result
.select
== 'function' ) {
321 $.suggestions
.highlight( context
, selected
, true );
322 context
.config
.result
.select
.call( selected
, context
.data
.$textbox
);
324 $.suggestions
.highlight( context
, selected
, true );
329 $.suggestions
.update( context
, true );
332 if ( preventDefault
) {
334 e
.stopImmediatePropagation();
338 $.fn
.suggestions = function() {
340 // Multi-context fields
341 var returnValue
= null;
342 var args
= arguments
;
344 $(this).each( function() {
346 /* Construction / Loading */
348 var context
= $(this).data( 'suggestions-context' );
349 if ( typeof context
== 'undefined' || context
== null ) {
352 'fetch' : function() {},
353 'cancel': function() {},
360 'submitOnClick': false,
361 'maxExpandFactor': 3,
362 'positionFromLeft': true,
363 'highlightInput': false
370 // Handle various calling styles
371 if ( args
.length
> 0 ) {
372 if ( typeof args
[0] == 'object' ) {
373 // Apply set of properties
374 for ( var key
in args
[0] ) {
375 $.suggestions
.configure( context
, key
, args
[0][key
] );
377 } else if ( typeof args
[0] == 'string' ) {
378 if ( args
.length
> 1 ) {
379 // Set property values
380 $.suggestions
.configure( context
, args
[0], args
[1] );
381 } else if ( returnValue
== null ) {
382 // Get property values, but don't give access to internal data - returns only the first
383 returnValue
= ( args
[0] in context
.config
? undefined : context
.config
[args
[0]] );
390 if ( typeof context
.data
== 'undefined' ) {
392 // ID of running timer
394 // Text in textbox when suggestions were last fetched
396 // Number of results visible without scrolling
398 // Suggestion the last mousedown event occured on
399 'mouseDownOn': $( [] ),
401 'selectedWithMouse': false
403 // Setup the css for positioning the results box
405 'top': Math
.round( context
.data
.$textbox
.offset().top
+ context
.data
.$textbox
.outerHeight() ),
406 'width': context
.data
.$textbox
.outerWidth(),
409 if ( context
.config
.positionFromLeft
) {
410 newCSS
['left'] = context
.config
.$region
.offset().left
;
411 newCSS
['right'] = 'auto';
413 newCSS
['left'] = 'auto';
414 newCSS
['right'] = $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
417 context
.data
.$container
= $( '<div />' )
419 .addClass( 'suggestions' )
421 $( '<div />' ).addClass( 'suggestions-results' )
422 // Can't use click() because the container div is hidden when the textbox loses focus. Instead,
423 // listen for a mousedown followed by a mouseup on the same div
424 .mousedown( function( e
) {
425 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results div' );
427 .mouseup( function( e
) {
428 var $result
= $( e
.target
).closest( '.suggestions-results div' );
429 var $other
= context
.data
.mouseDownOn
;
430 context
.data
.mouseDownOn
= $( [] );
431 if ( $result
.get( 0 ) != $other
.get( 0 ) ) {
434 $.suggestions
.highlight( context
, $result
, true );
435 context
.data
.$container
.hide();
436 if ( typeof context
.config
.result
.select
== 'function' ) {
437 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
);
439 context
.data
.$textbox
.focus();
443 $( '<div />' ).addClass( 'suggestions-special' )
444 // Can't use click() because the container div is hidden when the textbox loses focus. Instead,
445 // listen for a mousedown followed by a mouseup on the same div
446 .mousedown( function( e
) {
447 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
449 .mouseup( function( e
) {
450 var $special
= $( e
.target
).closest( '.suggestions-special' );
451 var $other
= context
.data
.mouseDownOn
;
452 context
.data
.mouseDownOn
= $( [] );
453 if ( $special
.get( 0 ) != $other
.get( 0 ) ) {
456 context
.data
.$container
.hide();
457 if ( typeof context
.config
.special
.select
== 'function' ) {
458 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
);
460 context
.data
.$textbox
.focus();
462 .mousemove( function( e
) {
463 context
.data
.selectedWithMouse
= true;
464 $.suggestions
.highlight(
465 context
, $( e
.target
).closest( '.suggestions-special' ), false
469 .appendTo( $( 'body' ) );
471 // Stop browser autocomplete from interfering
472 .attr( 'autocomplete', 'off')
473 .keydown( function( e
) {
474 // Store key pressed to handle later
475 context
.data
.keypressed
= ( e
.keyCode
== undefined ) ? e
.which
: e
.keyCode
;
476 context
.data
.keypressedCount
= 0;
478 switch ( context
.data
.keypressed
) {
479 // This preventDefault logic is duplicated from
480 // $.suggestions.keypress(), which sucks
483 e
.stopImmediatePropagation();
488 if ( context
.data
.$container
.is( ':visible' ) ) {
490 e
.stopImmediatePropagation();
494 .keypress( function( e
) {
495 context
.data
.keypressedCount
++;
496 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
498 .keyup( function( e
) {
499 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
500 // keypress in between, solve it
501 if ( context
.data
.keypressedCount
== 0 ) {
502 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
506 // When losing focus because of a mousedown
507 // on a suggestion, don't hide the suggestions
508 if ( context
.data
.mouseDownOn
.length
> 0 ) {
511 context
.data
.$container
.hide();
512 $.suggestions
.cancel( context
);
515 // Store the context for next time
516 $(this).data( 'suggestions-context', context
);
518 return returnValue
!== null ? returnValue
: $(this);