2 * This plugin provides a generic way to add suggestions to a text box.
6 * $( '#textbox' ).suggestions( { option1: value1, option2: value2 } );
7 * $( '#textbox' ).suggestions( option, value );
11 * value = $( '#textbox' ).suggestions( option );
15 * $( '#textbox' ).suggestions();
17 * Uses jQuery.suggestions singleteon internally.
19 * @class jQuery.plugin.suggestions
27 * @param {Object} options
29 * @param {Function} [options.fetch] Callback that should fetch suggestions and set the suggestions
30 * property. Called in context of the text box.
31 * @param {string} options.fetch.query
32 * @param {Function} options.fetch.response Callback to receive the suggestions with
33 * @param {Array} options.fetch.response.suggestions
34 * @param {number} options.fetch.maxRows
36 * @param {Function} [options.cancel] Callback function to call when any pending asynchronous
37 * suggestions fetches. Called in context of the text box.
39 * @param {Object} [options.special] Set of callbacks for rendering and selecting.
41 * @param {Function} options.special.render Called in context of the suggestions-special element.
42 * @param {string} options.special.render.query
43 * @param {Object} options.special.render.context
45 * @param {Function} options.special.select Called in context of the suggestions-result-current element.
46 * @param {jQuery} options.special.select.$textbox
48 * @param {Object} [options.result] Set of callbacks for rendering and selecting
50 * @param {Function} options.result.render Called in context of the suggestions-result element.
51 * @param {string} options.result.render.suggestion
52 * @param {Object} options.result.render.context
54 * @param {Function} options.result.select Called in context of the suggestions-result-current element.
55 * @param {jQuery} options.result.select.$textbox
57 * @param {Object} [options.update] Set of callbacks for listening to a change in the text input.
59 * @param {Function} options.update.before Called right after the user changes the textbox text.
60 * @param {Function} options.update.after Called after results are updated either from the cache or
61 * the API as a result of the user input.
63 * @param {jQuery} [options.$region=this] The element to place the suggestions below and match width of.
65 * @param {string[]} [options.suggestions] Array of suggestions to display.
67 * @param {number} [options.maxRows=10] Maximum number of suggestions to display at one time.
68 * Must be between 1 and 100.
70 * @param {number} [options.delay=120] Number of milliseconds to wait for the user to stop typing.
71 * Must be between 0 and 1200.
73 * @param {boolean} [options.cache=false] Whether to cache results from a fetch.
75 * @param {number} [options.cacheMaxAge=60000] Number of milliseconds to cache results from a fetch.
76 * Must be higher than 1. Defaults to 1 minute.
78 * @param {boolean} [options.submitOnClick=false] Whether to submit the form containing the textbox
79 * when a suggestion is clicked.
81 * @param {number} [options.maxExpandFactor=3] Maximum suggestions box width relative to the textbox
82 * width. If set to e.g. 2, the suggestions box will never be grown beyond 2 times the width of
83 * the textbox. Must be higher than 1.
85 * @param {string} [options.expandFrom=auto] Which direction to offset the suggestion box from.
86 * Values 'start' and 'end' translate to left and right respectively depending on the directionality
87 * of the current document, according to `$( 'html' ).css( 'direction' )`.
88 * Valid values: "left", "right", "start", "end", and "auto".
90 * @param {boolean} [options.positionFromLeft] Sets `expandFrom=left`, for backwards
93 * @param {boolean} [options.highlightInput=false] Whether to highlight matched portions of the
99 var hasOwn
= Object
.hasOwnProperty
;
102 * Used by jQuery.plugin.suggestions.
104 * @class jQuery.suggestions
110 * Cancel any delayed maybeFetch() call and callback the context so
111 * they can cancel any async fetching if they use AJAX or something.
113 cancel: function ( context
) {
114 if ( context
.data
.timerID
!== null ) {
115 clearTimeout( context
.data
.timerID
);
117 if ( $.isFunction( context
.config
.cancel
) ) {
118 context
.config
.cancel
.call( context
.data
.$textbox
);
123 * Hide the element with suggestions and clean up some state.
125 hide: function ( context
) {
126 // Remove any highlights, including on "special" items
127 context
.data
.$container
.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
128 // Hide the container
129 context
.data
.$container
.hide();
133 * Restore the text the user originally typed in the textbox, before it
134 * was overwritten by highlight(). This restores the value the currently
135 * displayed suggestions are based on, rather than the value just before
136 * highlight() overwrote it; the former is arguably slightly more sensible.
138 restore: function ( context
) {
139 context
.data
.$textbox
.val( context
.data
.prevText
);
143 * Ask the user-specified callback for new suggestions. Any previous delayed
144 * call to this function still pending will be canceled. If the value in the
145 * textbox is empty or hasn't changed since the last time suggestions were fetched,
146 * this function does nothing.
148 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
150 update: function ( context
, delayed
) {
151 function maybeFetch() {
152 var val
= context
.data
.$textbox
.val(),
153 cache
= context
.data
.cache
,
156 if ( typeof context
.config
.update
.before
=== 'function' ) {
157 context
.config
.update
.before
.call( context
.data
.$textbox
);
160 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
161 // if the textbox is empty then clear the result div, but leave other settings intouched
162 if ( val
.length
=== 0 ) {
163 $.suggestions
.hide( context
);
164 context
.data
.prevText
= '';
166 val
!== context
.data
.prevText
||
167 !context
.data
.$container
.is( ':visible' )
169 context
.data
.prevText
= val
;
171 if ( context
.config
.cache
&& hasOwn
.call( cache
, val
) ) {
172 if ( +new Date() - cache
[ val
].timestamp
< context
.config
.cacheMaxAge
) {
173 context
.data
.$textbox
.suggestions( 'suggestions', cache
[ val
].suggestions
);
174 if ( typeof context
.config
.update
.after
=== 'function' ) {
175 context
.config
.update
.after
.call( context
.data
.$textbox
);
183 if ( !cacheHit
&& typeof context
.config
.fetch
=== 'function' ) {
184 context
.config
.fetch
.call(
185 context
.data
.$textbox
,
187 function ( suggestions
) {
188 suggestions
= suggestions
.slice( 0, context
.config
.maxRows
);
189 context
.data
.$textbox
.suggestions( 'suggestions', suggestions
);
190 if ( typeof context
.config
.update
.after
=== 'function' ) {
191 context
.config
.update
.after
.call( context
.data
.$textbox
);
193 if ( context
.config
.cache
) {
195 suggestions
: suggestions
,
196 timestamp
: +new Date()
200 context
.config
.maxRows
205 // Always update special rendering
206 $.suggestions
.special( context
);
209 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
210 $.suggestions
.cancel( context
);
213 // To avoid many started/aborted requests while typing, we're gonna take a short
214 // break before trying to fetch data.
215 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
221 special: function ( context
) {
222 // Allow custom rendering - but otherwise don't do any rendering
223 if ( typeof context
.config
.special
.render
=== 'function' ) {
224 // Wait for the browser to update the value
225 setTimeout( function () {
227 var $special
= context
.data
.$container
.find( '.suggestions-special' );
228 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val(), context
);
234 * Sets the value of a property, and updates the widget accordingly
236 * @param {string} property Name of property
237 * @param {Mixed} value Value to set property with
239 configure: function ( context
, property
, value
) {
241 $result
, $results
, $spanForWidth
, childrenWidth
,
242 i
, expWidth
, maxWidth
, text
;
244 // Validate creation using fallback values
245 switch ( property
) {
253 context
.config
[ property
] = value
;
256 context
.config
[ property
] = value
;
257 // Update suggestions
258 if ( context
.data
!== undefined ) {
259 if ( context
.data
.$textbox
.val().length
=== 0 ) {
260 // Hide the div when no suggestion exist
261 $.suggestions
.hide( context
);
263 // Rebuild the suggestions list
264 context
.data
.$container
.show();
265 // Update the size and position of the list
267 top
: context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
269 width
: context
.config
.$region
.outerWidth(),
273 // Process expandFrom, after this it is set to left or right.
274 context
.config
.expandFrom
= ( function ( expandFrom
) {
275 var regionWidth
, docWidth
, regionCenter
, docCenter
,
276 docDir
= $( document
.documentElement
).css( 'direction' ),
277 $region
= context
.config
.$region
;
279 // Backwards compatible
280 if ( context
.config
.positionFromLeft
) {
283 // Catch invalid values, default to 'auto'
284 } else if ( $.inArray( expandFrom
, [ 'left', 'right', 'start', 'end', 'auto' ] ) === -1 ) {
288 if ( expandFrom
=== 'auto' ) {
289 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
290 // If the markup explicitly contains a direction, use it.
291 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
293 regionWidth
= $region
.outerWidth();
294 docWidth
= $( document
).width();
295 if ( regionWidth
> ( 0.85 * docWidth
) ) {
296 // If the input size takes up more than 85% of the document horizontally
297 // expand the suggestions to the writing direction's native end.
298 expandFrom
= 'start';
300 // Calculate the center points of the input and document
301 regionCenter
= $region
.offset().left
+ regionWidth
/ 2;
302 docCenter
= docWidth
/ 2;
303 if ( Math
.abs( regionCenter
- docCenter
) < ( 0.10 * docCenter
) ) {
304 // If the input's center is within 10% of the document center
305 // use the writing direction's native end.
306 expandFrom
= 'start';
308 // Otherwise expand the input from the closest side of the page,
309 // towards the side of the page with the most free open space
310 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
316 if ( expandFrom
=== 'start' ) {
317 expandFrom
= docDir
=== 'rtl' ? 'right' : 'left';
319 } else if ( expandFrom
=== 'end' ) {
320 expandFrom
= docDir
=== 'rtl' ? 'left' : 'right';
325 }( context
.config
.expandFrom
) );
327 if ( context
.config
.expandFrom
=== 'left' ) {
329 newCSS
.left
= context
.config
.$region
.offset().left
;
330 newCSS
.right
= 'auto';
333 newCSS
.left
= 'auto';
334 newCSS
.right
= $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
337 context
.data
.$container
.css( newCSS
);
338 $results
= context
.data
.$container
.children( '.suggestions-results' );
341 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
342 /*jshint loopfunc:true */
343 text
= context
.config
.suggestions
[ i
];
344 $result
= $( '<div>' )
345 .addClass( 'suggestions-result' )
347 .data( 'text', context
.config
.suggestions
[ i
] )
348 .mousemove( function () {
349 context
.data
.selectedWithMouse
= true;
350 $.suggestions
.highlight(
352 $( this ).closest( '.suggestions-results .suggestions-result' ),
356 .appendTo( $results
);
357 // Allow custom rendering
358 if ( typeof context
.config
.result
.render
=== 'function' ) {
359 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[ i
], context
);
361 $result
.text( text
);
364 if ( context
.config
.highlightInput
) {
365 $result
.highlightText( context
.data
.prevText
);
368 // Widen results box if needed (new width is only calculated here, applied later).
370 // The monstrosity below accomplishes two things:
371 // * Wraps the text contents in a DOM element, so that we can know its width. There is
372 // no way to directly access the width of a text node, and we can't use the parent
373 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
374 // it, which trims it to a smaller width.
375 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
376 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
377 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
378 // still report the "trimmed" width. This should not be done in regular CSS
379 // stylesheets as we don't want this rule to apply to other <span> elements, like
380 // the ones generated by jquery.highlightText.
381 $spanForWidth
= $result
.wrapInner( '<span>' ).children();
382 childrenWidth
= $spanForWidth
.css( 'position', 'absolute' ).outerWidth();
383 $spanForWidth
.contents().unwrap();
385 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
386 // factor in any padding, margin, or border space on the parent
387 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
391 // Apply new width for results box, if any
392 if ( expWidth
> context
.data
.$container
.width() ) {
393 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
394 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
400 context
.config
[ property
] = Math
.max( 1, Math
.min( 100, value
) );
403 context
.config
[ property
] = Math
.max( 0, Math
.min( 1200, value
) );
406 context
.config
[ property
] = Math
.max( 1, value
);
408 case 'maxExpandFactor':
409 context
.config
[ property
] = Math
.max( 1, value
);
412 case 'submitOnClick':
413 case 'positionFromLeft':
414 case 'highlightInput':
415 context
.config
[ property
] = !!value
;
421 * Highlight a result in the results table
423 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
424 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
426 highlight: function ( context
, result
, updateTextbox
) {
427 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
428 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
429 if ( result
=== 'prev' ) {
430 if ( selected
.hasClass( 'suggestions-special' ) ) {
431 result
= context
.data
.$container
.find( '.suggestions-result:last' );
433 result
= selected
.prev();
434 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
435 // there is something in the DOM between selected element and the wrapper, bypass it
436 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
439 if ( selected
.length
=== 0 ) {
440 // we are at the beginning, so lets jump to the last item
441 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
442 result
= context
.data
.$container
.find( '.suggestions-special' );
444 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:last' );
448 } else if ( result
=== 'next' ) {
449 if ( selected
.length
=== 0 ) {
450 // No item selected, go to the first one
451 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:first' );
452 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
453 // No suggestion exists, go to the special one directly
454 result
= context
.data
.$container
.find( '.suggestions-special' );
457 result
= selected
.next();
458 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
459 // there is something in the DOM between selected element and the wrapper, bypass it
460 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
463 if ( selected
.hasClass( 'suggestions-special' ) ) {
466 result
.length
=== 0 &&
467 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
469 // We were at the last item, jump to the specials!
470 result
= context
.data
.$container
.find( '.suggestions-special' );
474 selected
.removeClass( 'suggestions-result-current' );
475 result
.addClass( 'suggestions-result-current' );
477 if ( updateTextbox
) {
478 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
479 $.suggestions
.restore( context
);
481 context
.data
.$textbox
.val( result
.data( 'text' ) );
482 // .val() doesn't call any event handlers, so
483 // let the world know what happened
484 context
.data
.$textbox
.change();
486 context
.data
.$textbox
.trigger( 'change' );
491 * Respond to keypress event
493 * @param {number} key Code of key pressed
495 keypress: function ( e
, context
, key
) {
497 wasVisible
= context
.data
.$container
.is( ':visible' ),
498 preventDefault
= false;
504 $.suggestions
.highlight( context
, 'next', true );
505 context
.data
.selectedWithMouse
= false;
507 $.suggestions
.update( context
, false );
509 preventDefault
= true;
514 $.suggestions
.highlight( context
, 'prev', true );
515 context
.data
.selectedWithMouse
= false;
517 preventDefault
= wasVisible
;
521 $.suggestions
.hide( context
);
522 $.suggestions
.restore( context
);
523 $.suggestions
.cancel( context
);
524 context
.data
.$textbox
.trigger( 'change' );
525 preventDefault
= wasVisible
;
529 preventDefault
= wasVisible
;
530 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
531 $.suggestions
.hide( context
);
532 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
533 // If nothing is selected or if something was selected with the mouse
534 // cancel any current requests and allow the form to be submitted
535 // (simply don't prevent default behavior).
536 $.suggestions
.cancel( context
);
537 preventDefault
= false;
538 } else if ( selected
.is( '.suggestions-special' ) ) {
539 if ( typeof context
.config
.special
.select
=== 'function' ) {
540 // Allow the callback to decide whether to prevent default or not
541 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
) === true ) {
542 preventDefault
= false;
546 if ( typeof context
.config
.result
.select
=== 'function' ) {
547 // Allow the callback to decide whether to prevent default or not
548 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
) === true ) {
549 preventDefault
= false;
555 $.suggestions
.update( context
, true );
558 if ( preventDefault
) {
565 // See file header for method documentation
566 $.fn
.suggestions = function () {
568 // Multi-context fields
572 $( this ).each( function () {
575 /* Construction and Loading */
577 context
= $( this ).data( 'suggestions-context' );
578 if ( context
=== undefined || context
=== null ) {
581 fetch: function () {},
582 cancel: function () {},
592 submitOnClick
: false,
595 highlightInput
: false
602 // Handle various calling styles
603 if ( args
.length
> 0 ) {
604 if ( typeof args
[ 0 ] === 'object' ) {
605 // Apply set of properties
606 for ( key
in args
[ 0 ] ) {
607 $.suggestions
.configure( context
, key
, args
[ 0 ][ key
] );
609 } else if ( typeof args
[ 0 ] === 'string' ) {
610 if ( args
.length
> 1 ) {
611 // Set property values
612 $.suggestions
.configure( context
, args
[ 0 ], args
[ 1 ] );
613 } else if ( returnValue
=== null || returnValue
=== undefined ) {
614 // Get property values, but don't give access to internal data - returns only the first
615 returnValue
= ( args
[ 0 ] in context
.config
? undefined : context
.config
[ args
[ 0 ] ] );
622 if ( context
.data
=== undefined ) {
624 // ID of running timer
627 // Text in textbox when suggestions were last fetched
630 // Cache of fetched suggestions
633 // Number of results visible without scrolling
636 // Suggestion the last mousedown event occurred on
637 mouseDownOn
: $( [] ),
639 selectedWithMouse
: false
642 context
.data
.$container
= $( '<div>' )
643 .css( 'display', 'none' )
644 .addClass( 'suggestions' )
646 $( '<div>' ).addClass( 'suggestions-results' )
647 // Can't use click() because the container div is hidden when the
648 // textbox loses focus. Instead, listen for a mousedown followed
649 // by a mouseup on the same div.
650 .mousedown( function ( e
) {
651 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
653 .mouseup( function ( e
) {
654 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
655 $other
= context
.data
.mouseDownOn
;
657 context
.data
.mouseDownOn
= $( [] );
658 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
661 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
662 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
663 $.suggestions
.highlight( context
, $result
, true );
664 if ( typeof context
.config
.result
.select
=== 'function' ) {
665 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
);
667 // This will hide the link we're just clicking on, which causes problems
668 // when done synchronously in at least Firefox 3.6 (bug 62858).
669 setTimeout( function () {
670 $.suggestions
.hide( context
);
673 // Always bring focus to the textbox, as that's probably where the user expects it
674 // if they were just typing.
675 context
.data
.$textbox
.focus();
679 $( '<div>' ).addClass( 'suggestions-special' )
680 // Can't use click() because the container div is hidden when the
681 // textbox loses focus. Instead, listen for a mousedown followed
682 // by a mouseup on the same div.
683 .mousedown( function ( e
) {
684 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
686 .mouseup( function ( e
) {
687 var $special
= $( e
.target
).closest( '.suggestions-special' ),
688 $other
= context
.data
.mouseDownOn
;
690 context
.data
.mouseDownOn
= $( [] );
691 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
694 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
695 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
696 if ( typeof context
.config
.special
.select
=== 'function' ) {
697 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
);
699 // This will hide the link we're just clicking on, which causes problems
700 // when done synchronously in at least Firefox 3.6 (bug 62858).
701 setTimeout( function () {
702 $.suggestions
.hide( context
);
705 // Always bring focus to the textbox, as that's probably where the user expects it
706 // if they were just typing.
707 context
.data
.$textbox
.focus();
709 .mousemove( function ( e
) {
710 context
.data
.selectedWithMouse
= true;
711 $.suggestions
.highlight(
712 context
, $( e
.target
).closest( '.suggestions-special' ), false
716 .appendTo( $( 'body' ) );
719 // Stop browser autocomplete from interfering
720 .attr( 'autocomplete', 'off' )
721 .keydown( function ( e
) {
722 // Store key pressed to handle later
723 context
.data
.keypressed
= e
.which
;
724 context
.data
.keypressedCount
= 0;
726 .keypress( function ( e
) {
727 context
.data
.keypressedCount
++;
728 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
730 .keyup( function ( e
) {
731 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
732 // keypress in between, solve it
733 if ( context
.data
.keypressedCount
=== 0 ) {
734 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
738 // When losing focus because of a mousedown
739 // on a suggestion, don't hide the suggestions
740 if ( context
.data
.mouseDownOn
.length
> 0 ) {
743 $.suggestions
.hide( context
);
744 $.suggestions
.cancel( context
);
748 // Store the context for next time
749 $( this ).data( 'suggestions-context', context
);
751 return returnValue
!== undefined ? returnValue
: $( this );
756 * @mixins jQuery.plugin.suggestions