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.
17 * Executed in the context of the textbox
19 * cancel: Callback function to call when any pending asynchronous suggestions fetches
20 * should be canceled. 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
37 * to e.g. 2, the suggestions box will never be grown beyond 2 times the width of the textbox.
38 * Type: Number, Range: 1 - infinity, Default: 3
39 * expandFrom: Which direction to offset the suggestion box from.
40 * Values 'start' and 'end' translate to left and right respectively depending on the
41 * directionality of the current document, according to $( 'html' ).css( 'direction' ).
42 * Type: String, default: 'auto', options: 'left', 'right', 'start', 'end', 'auto'.
43 * positionFromLeft: Sets expandFrom=left, for backwards compatibility
44 * Type: Boolean, Default: true
45 * highlightInput: Whether to hightlight matched portions of the input or not
46 * Type: Boolean, Default: false
52 * Cancel any delayed maybeFetch() call and callback the context so
53 * they can cancel any async fetching if they use AJAX or something.
55 cancel: function ( context
) {
56 if ( context
.data
.timerID
!== null ) {
57 clearTimeout( context
.data
.timerID
);
59 if ( $.isFunction( context
.config
.cancel
) ) {
60 context
.config
.cancel
.call( context
.data
.$textbox
);
65 * Hide the element with suggestions and clean up some state.
67 hide: function ( context
) {
68 // Remove any highlights, including on "special" items
69 context
.data
.$container
.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
71 context
.data
.$container
.hide();
75 * Restore the text the user originally typed in the textbox, before it
76 * was overwritten by highlight(). This restores the value the currently
77 * displayed suggestions are based on, rather than the value just before
78 * highlight() overwrote it; the former is arguably slightly more sensible.
80 restore: function ( context
) {
81 context
.data
.$textbox
.val( context
.data
.prevText
);
85 * Ask the user-specified callback for new suggestions. Any previous delayed
86 * call to this function still pending will be canceled. If the value in the
87 * textbox is empty or hasn't changed since the last time suggestions were fetched,
88 * this function does nothing.
89 * @param {Boolean} delayed Whether or not to delay this by the currently configured amount of time
91 update: function ( context
, delayed
) {
92 function maybeFetch() {
93 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
94 // if the textbox is empty then clear the result div, but leave other settings intouched
95 if ( context
.data
.$textbox
.val().length
=== 0 ) {
96 $.suggestions
.hide( context
);
97 context
.data
.prevText
= '';
99 context
.data
.$textbox
.val() !== context
.data
.prevText
||
100 !context
.data
.$container
.is( ':visible' )
102 if ( typeof context
.config
.fetch
=== 'function' ) {
103 context
.data
.prevText
= context
.data
.$textbox
.val();
104 context
.config
.fetch
.call( context
.data
.$textbox
, context
.data
.$textbox
.val() );
108 // Always update special rendering
109 $.suggestions
.special( context
);
112 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
113 $.suggestions
.cancel( context
);
116 // To avoid many started/aborted requests while typing, we're gonna take a short
117 // break before trying to fetch data.
118 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
124 special: function ( context
) {
125 // Allow custom rendering - but otherwise don't do any rendering
126 if ( typeof context
.config
.special
.render
=== 'function' ) {
127 // Wait for the browser to update the value
128 setTimeout( function () {
130 var $special
= context
.data
.$container
.find( '.suggestions-special' );
131 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val(), context
);
137 * Sets the value of a property, and updates the widget accordingly
138 * @param property String Name of property
139 * @param value Mixed Value to set property with
141 configure: function ( context
, property
, value
) {
143 $result
, $results
, $spanForWidth
, childrenWidth
,
144 i
, expWidth
, maxWidth
, text
;
146 // Validate creation using fallback values
147 switch ( property
) {
154 context
.config
[property
] = value
;
157 context
.config
[property
] = value
;
158 // Update suggestions
159 if ( context
.data
!== undefined ) {
160 if ( context
.data
.$textbox
.val().length
=== 0 ) {
161 // Hide the div when no suggestion exist
162 $.suggestions
.hide( context
);
164 // Rebuild the suggestions list
165 context
.data
.$container
.show();
166 // Update the size and position of the list
168 top
: context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
170 width
: context
.config
.$region
.outerWidth(),
174 // Process expandFrom, after this it is set to left or right.
175 context
.config
.expandFrom
= ( function ( expandFrom
) {
176 var regionWidth
, docWidth
, regionCenter
, docCenter
,
177 docDir
= $( document
.documentElement
).css( 'direction' ),
178 $region
= context
.config
.$region
;
180 // Backwards compatible
181 if ( context
.config
.positionFromLeft
) {
184 // Catch invalid values, default to 'auto'
185 } else if ( $.inArray( expandFrom
, ['left', 'right', 'start', 'end', 'auto'] ) === -1 ) {
189 if ( expandFrom
=== 'auto' ) {
190 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
191 // If the markup explicitly contains a direction, use it.
192 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
194 regionWidth
= $region
.outerWidth();
195 docWidth
= $( document
).width();
196 if ( ( regionWidth
/ docWidth
) > 0.85 ) {
197 // If the input size takes up more than 85% of the document horizontally
198 // expand the suggestions to the writing direction's native end.
199 expandFrom
= 'start';
201 // Calculate the center points of the input and document
202 regionCenter
= $region
.offset().left
+ regionWidth
/ 2;
203 docCenter
= docWidth
/ 2;
204 if ( Math
.abs( regionCenter
- docCenter
) / docCenter
< 0.10 ) {
205 // If the input's center is within 10% of the document center
206 // use the writing direction's native end.
207 expandFrom
= 'start';
209 // Otherwise expand the input from the closest side of the page,
210 // towards the side of the page with the most free open space
211 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
217 if ( expandFrom
=== 'start' ) {
218 expandFrom
= docDir
=== 'rtl' ? 'right' : 'left';
220 } else if ( expandFrom
=== 'end' ) {
221 expandFrom
= docDir
=== 'rtl' ? 'left' : 'right';
226 }( context
.config
.expandFrom
) );
228 if ( context
.config
.expandFrom
=== 'left' ) {
230 newCSS
.left
= context
.config
.$region
.offset().left
;
231 newCSS
.right
= 'auto';
234 newCSS
.left
= 'auto';
235 newCSS
.right
= $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
238 context
.data
.$container
.css( newCSS
);
239 $results
= context
.data
.$container
.children( '.suggestions-results' );
242 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
243 /*jshint loopfunc:true */
244 text
= context
.config
.suggestions
[i
];
245 $result
= $( '<div>' )
246 .addClass( 'suggestions-result' )
248 .data( 'text', context
.config
.suggestions
[i
] )
249 .mousemove( function () {
250 context
.data
.selectedWithMouse
= true;
251 $.suggestions
.highlight(
253 $( this ).closest( '.suggestions-results .suggestions-result' ),
257 .appendTo( $results
);
258 // Allow custom rendering
259 if ( typeof context
.config
.result
.render
=== 'function' ) {
260 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[i
], context
);
262 $result
.text( text
);
265 if ( context
.config
.highlightInput
) {
266 $result
.highlightText( context
.data
.prevText
);
269 // Widen results box if needed (new width is only calculated here, applied later).
270 // We need this awful hack to calculate the actual pre-ellipsis width.
271 $spanForWidth
= $result
.wrapInner( '<span>' ).children();
272 childrenWidth
= $spanForWidth
.outerWidth();
273 $spanForWidth
.contents().unwrap();
274 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
275 // factor in any padding, margin, or border space on the parent
276 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
280 // Apply new width for results box, if any
281 if ( expWidth
> context
.data
.$container
.width() ) {
282 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
283 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
289 context
.config
[property
] = Math
.max( 1, Math
.min( 100, value
) );
292 context
.config
[property
] = Math
.max( 0, Math
.min( 1200, value
) );
294 case 'maxExpandFactor':
295 context
.config
[property
] = Math
.max( 1, value
);
297 case 'submitOnClick':
298 case 'positionFromLeft':
299 case 'highlightInput':
300 context
.config
[property
] = value
? true : false;
306 * Highlight a result in the results table
307 * @param result <tr> to highlight: jQuery object, or 'prev' or 'next'
308 * @param updateTextbox If true, put the suggestion in the textbox
310 highlight: function ( context
, result
, updateTextbox
) {
311 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
312 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
313 if ( result
=== 'prev' ) {
314 if ( selected
.hasClass( 'suggestions-special' ) ) {
315 result
= context
.data
.$container
.find( '.suggestions-result:last' );
317 result
= selected
.prev();
318 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
319 // there is something in the DOM between selected element and the wrapper, bypass it
320 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
323 if ( selected
.length
=== 0 ) {
324 // we are at the beginning, so lets jump to the last item
325 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
326 result
= context
.data
.$container
.find( '.suggestions-special' );
328 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:last' );
332 } else if ( result
=== 'next' ) {
333 if ( selected
.length
=== 0 ) {
334 // No item selected, go to the first one
335 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:first' );
336 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
337 // No suggestion exists, go to the special one directly
338 result
= context
.data
.$container
.find( '.suggestions-special' );
341 result
= selected
.next();
342 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
343 // there is something in the DOM between selected element and the wrapper, bypass it
344 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
347 if ( selected
.hasClass( 'suggestions-special' ) ) {
350 result
.length
=== 0 &&
351 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
353 // We were at the last item, jump to the specials!
354 result
= context
.data
.$container
.find( '.suggestions-special' );
358 selected
.removeClass( 'suggestions-result-current' );
359 result
.addClass( 'suggestions-result-current' );
361 if ( updateTextbox
) {
362 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
363 $.suggestions
.restore( context
);
365 context
.data
.$textbox
.val( result
.data( 'text' ) );
366 // .val() doesn't call any event handlers, so
367 // let the world know what happened
368 context
.data
.$textbox
.change();
370 context
.data
.$textbox
.trigger( 'change' );
375 * Respond to keypress event
376 * @param key Integer Code of key pressed
378 keypress: function ( e
, context
, key
) {
380 wasVisible
= context
.data
.$container
.is( ':visible' ),
381 preventDefault
= false;
387 $.suggestions
.highlight( context
, 'next', true );
388 context
.data
.selectedWithMouse
= false;
390 $.suggestions
.update( context
, false );
392 preventDefault
= true;
397 $.suggestions
.highlight( context
, 'prev', true );
398 context
.data
.selectedWithMouse
= false;
400 preventDefault
= wasVisible
;
404 $.suggestions
.hide( context
);
405 $.suggestions
.restore( context
);
406 $.suggestions
.cancel( context
);
407 context
.data
.$textbox
.trigger( 'change' );
408 preventDefault
= wasVisible
;
412 preventDefault
= wasVisible
;
413 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
414 $.suggestions
.hide( context
);
415 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
416 // If nothing is selected or if something was selected with the mouse
417 // cancel any current requests and allow the form to be submitted
418 // (simply don't prevent default behavior).
419 $.suggestions
.cancel( context
);
420 preventDefault
= false;
421 } else if ( selected
.is( '.suggestions-special' ) ) {
422 if ( typeof context
.config
.special
.select
=== 'function' ) {
423 // Allow the callback to decide whether to prevent default or not
424 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
) === true ) {
425 preventDefault
= false;
429 $.suggestions
.highlight( context
, selected
, true );
431 if ( typeof context
.config
.result
.select
=== 'function' ) {
432 // Allow the callback to decide whether to prevent default or not
433 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
) === true ) {
434 preventDefault
= false;
440 $.suggestions
.update( context
, true );
443 if ( preventDefault
) {
449 $.fn
.suggestions = function () {
451 // Multi-context fields
455 $( this ).each( function () {
458 /* Construction / Loading */
460 context
= $( this ).data( 'suggestions-context' );
461 if ( context
=== undefined || context
=== null ) {
464 fetch: function () {},
465 cancel: function () {},
472 submitOnClick
: false,
475 highlightInput
: false
482 // Handle various calling styles
483 if ( args
.length
> 0 ) {
484 if ( typeof args
[0] === 'object' ) {
485 // Apply set of properties
486 for ( key
in args
[0] ) {
487 $.suggestions
.configure( context
, key
, args
[0][key
] );
489 } else if ( typeof args
[0] === 'string' ) {
490 if ( args
.length
> 1 ) {
491 // Set property values
492 $.suggestions
.configure( context
, args
[0], args
[1] );
493 } else if ( returnValue
=== null || returnValue
=== undefined ) {
494 // Get property values, but don't give access to internal data - returns only the first
495 returnValue
= ( args
[0] in context
.config
? undefined : context
.config
[args
[0]] );
502 if ( context
.data
=== undefined ) {
504 // ID of running timer
507 // Text in textbox when suggestions were last fetched
510 // Number of results visible without scrolling
513 // Suggestion the last mousedown event occurred on
514 mouseDownOn
: $( [] ),
516 selectedWithMouse
: false
519 context
.data
.$container
= $( '<div>' )
520 .css( 'display', 'none' )
521 .addClass( 'suggestions' )
523 $( '<div>' ).addClass( 'suggestions-results' )
524 // Can't use click() because the container div is hidden when the
525 // textbox loses focus. Instead, listen for a mousedown followed
526 // by a mouseup on the same div.
527 .mousedown( function ( e
) {
528 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
530 .mouseup( function ( e
) {
531 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
532 $other
= context
.data
.mouseDownOn
;
534 context
.data
.mouseDownOn
= $( [] );
535 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
538 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
539 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
540 $.suggestions
.highlight( context
, $result
, true );
541 if ( typeof context
.config
.result
.select
=== 'function' ) {
542 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
);
544 // This will hide the link we're just clicking on, which causes problems
545 // when done synchronously in at least Firefox 3.6 (bug 62858).
546 setTimeout( function () {
547 $.suggestions
.hide( context
);
550 // Always bring focus to the textbox, as that's probably where the user expects it
551 // if they were just typing.
552 context
.data
.$textbox
.focus();
556 $( '<div>' ).addClass( 'suggestions-special' )
557 // Can't use click() because the container div is hidden when the
558 // textbox loses focus. Instead, listen for a mousedown followed
559 // by a mouseup on the same div.
560 .mousedown( function ( e
) {
561 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
563 .mouseup( function ( e
) {
564 var $special
= $( e
.target
).closest( '.suggestions-special' ),
565 $other
= context
.data
.mouseDownOn
;
567 context
.data
.mouseDownOn
= $( [] );
568 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
571 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
572 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
573 if ( typeof context
.config
.special
.select
=== 'function' ) {
574 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
);
576 // This will hide the link we're just clicking on, which causes problems
577 // when done synchronously in at least Firefox 3.6 (bug 62858).
578 setTimeout( function () {
579 $.suggestions
.hide( context
);
582 // Always bring focus to the textbox, as that's probably where the user expects it
583 // if they were just typing.
584 context
.data
.$textbox
.focus();
586 .mousemove( function ( e
) {
587 context
.data
.selectedWithMouse
= true;
588 $.suggestions
.highlight(
589 context
, $( e
.target
).closest( '.suggestions-special' ), false
593 .appendTo( $( 'body' ) );
596 // Stop browser autocomplete from interfering
597 .attr( 'autocomplete', 'off' )
598 .keydown( function ( e
) {
599 // Store key pressed to handle later
600 context
.data
.keypressed
= e
.which
;
601 context
.data
.keypressedCount
= 0;
603 .keypress( function ( e
) {
604 context
.data
.keypressedCount
++;
605 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
607 .keyup( function ( e
) {
608 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
609 // keypress in between, solve it
610 if ( context
.data
.keypressedCount
=== 0 ) {
611 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
615 // When losing focus because of a mousedown
616 // on a suggestion, don't hide the suggestions
617 if ( context
.data
.mouseDownOn
.length
> 0 ) {
620 $.suggestions
.hide( context
);
621 $.suggestions
.cancel( context
);
625 // Store the context for next time
626 $( this ).data( 'suggestions-context', context
);
628 return returnValue
!== undefined ? returnValue
: $( this );