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
26 * @param {Object} options
28 * @param {Function} [options.fetch] Callback that should fetch suggestions and set the suggestions
29 * property. Called in context of the text box.
30 * @param {string} options.fetch.query
31 * @param {Function} options.fetch.response Callback to receive the suggestions with
32 * @param {Array} options.fetch.response.suggestions
33 * @param {number} options.fetch.maxRows
35 * @param {Function} [options.cancel] Callback function to call when any pending asynchronous
36 * suggestions fetches. Called in context of the text box.
38 * @param {Object} [options.special] Set of callbacks for rendering and selecting.
40 * @param {Function} options.special.render Called in context of the suggestions-special element.
41 * @param {string} options.special.render.query
42 * @param {Object} options.special.render.context
44 * @param {Function} options.special.select Called in context of the suggestions-result-current element.
45 * @param {jQuery} options.special.select.$textbox
47 * @param {Object} [options.result] Set of callbacks for rendering and selecting
49 * @param {Function} options.result.render Called in context of the suggestions-result element.
50 * @param {string} options.result.render.suggestion
51 * @param {Object} options.result.render.context
53 * @param {Function} options.result.select Called in context of the suggestions-result-current element.
54 * @param {jQuery} options.result.select.$textbox
56 * @param {Object} [options.update] Set of callbacks for listening to a change in the text input.
58 * @param {Function} options.update.before Called right after the user changes the textbox text.
59 * @param {Function} options.update.after Called after results are updated either from the cache or
60 * the API as a result of the user input.
62 * @param {jQuery} [options.$region=this] The element to place the suggestions below and match width of.
64 * @param {string[]} [options.suggestions] Array of suggestions to display.
66 * @param {number} [options.maxRows=10] Maximum number of suggestions to display at one time.
67 * Must be between 1 and 100.
69 * @param {number} [options.delay=120] Number of milliseconds to wait for the user to stop typing.
70 * Must be between 0 and 1200.
72 * @param {boolean} [options.cache=false] Whether to cache results from a fetch.
74 * @param {number} [options.cacheMaxAge=60000] Number of milliseconds to cache results from a fetch.
75 * Must be higher than 1. Defaults to 1 minute.
77 * @param {boolean} [options.submitOnClick=false] Whether to submit the form containing the textbox
78 * when a suggestion is clicked.
80 * @param {number} [options.maxExpandFactor=3] Maximum suggestions box width relative to the textbox
81 * width. If set to e.g. 2, the suggestions box will never be grown beyond 2 times the width of
82 * the textbox. Must be higher than 1.
84 * @param {string} [options.expandFrom=auto] Which direction to offset the suggestion box from.
85 * Values 'start' and 'end' translate to left and right respectively depending on the directionality
86 * of the current document, according to `$( 'html' ).css( 'direction' )`.
87 * Valid values: "left", "right", "start", "end", and "auto".
89 * @param {boolean} [options.positionFromLeft] Sets `expandFrom=left`, for backwards
92 * @param {boolean} [options.highlightInput=false] Whether to highlight matched portions of the
97 var hasOwn
= Object
.hasOwnProperty
;
100 * Used by jQuery.plugin.suggestions.
102 * @class jQuery.suggestions
108 * Cancel any delayed maybeFetch() call and callback the context so
109 * they can cancel any async fetching if they use AJAX or something.
111 cancel: function ( context
) {
112 if ( context
.data
.timerID
!== null ) {
113 clearTimeout( context
.data
.timerID
);
115 if ( $.isFunction( context
.config
.cancel
) ) {
116 context
.config
.cancel
.call( context
.data
.$textbox
);
121 * Hide the element with suggestions and clean up some state.
123 hide: function ( context
) {
124 // Remove any highlights, including on "special" items
125 context
.data
.$container
.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
126 // Hide the container
127 context
.data
.$container
.hide();
131 * Restore the text the user originally typed in the textbox, before it
132 * was overwritten by highlight(). This restores the value the currently
133 * displayed suggestions are based on, rather than the value just before
134 * highlight() overwrote it; the former is arguably slightly more sensible.
136 restore: function ( context
) {
137 context
.data
.$textbox
.val( context
.data
.prevText
);
141 * Ask the user-specified callback for new suggestions. Any previous delayed
142 * call to this function still pending will be canceled. If the value in the
143 * textbox is empty or hasn't changed since the last time suggestions were fetched,
144 * this function does nothing.
146 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
148 update: function ( context
, delayed
) {
149 function maybeFetch() {
150 var val
= context
.data
.$textbox
.val(),
151 cache
= context
.data
.cache
,
154 if ( typeof context
.config
.update
.before
=== 'function' ) {
155 context
.config
.update
.before
.call( context
.data
.$textbox
);
158 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
159 // if the textbox is empty then clear the result div, but leave other settings intouched
160 if ( val
.length
=== 0 ) {
161 $.suggestions
.hide( context
);
162 context
.data
.prevText
= '';
164 val
!== context
.data
.prevText
||
165 !context
.data
.$container
.is( ':visible' )
167 context
.data
.prevText
= val
;
169 if ( context
.config
.cache
&& hasOwn
.call( cache
, val
) ) {
170 if ( +new Date() - cache
[ val
].timestamp
< context
.config
.cacheMaxAge
) {
171 context
.data
.$textbox
.suggestions( 'suggestions', cache
[ val
].suggestions
);
172 if ( typeof context
.config
.update
.after
=== 'function' ) {
173 context
.config
.update
.after
.call( context
.data
.$textbox
);
181 if ( !cacheHit
&& typeof context
.config
.fetch
=== 'function' ) {
182 context
.config
.fetch
.call(
183 context
.data
.$textbox
,
185 function ( suggestions
) {
186 suggestions
= suggestions
.slice( 0, context
.config
.maxRows
);
187 context
.data
.$textbox
.suggestions( 'suggestions', suggestions
);
188 if ( typeof context
.config
.update
.after
=== 'function' ) {
189 context
.config
.update
.after
.call( context
.data
.$textbox
);
191 if ( context
.config
.cache
) {
193 suggestions
: suggestions
,
194 timestamp
: +new Date()
198 context
.config
.maxRows
203 // Always update special rendering
204 $.suggestions
.special( context
);
207 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
208 $.suggestions
.cancel( context
);
211 // To avoid many started/aborted requests while typing, we're gonna take a short
212 // break before trying to fetch data.
213 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
219 special: function ( context
) {
220 // Allow custom rendering - but otherwise don't do any rendering
221 if ( typeof context
.config
.special
.render
=== 'function' ) {
222 // Wait for the browser to update the value
223 setTimeout( function () {
225 var $special
= context
.data
.$container
.find( '.suggestions-special' );
226 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val(), context
);
232 * Sets the value of a property, and updates the widget accordingly
234 * @param {string} property Name of property
235 * @param {Mixed} value Value to set property with
237 configure: function ( context
, property
, value
) {
239 $result
, $results
, $spanForWidth
, childrenWidth
,
240 i
, expWidth
, maxWidth
, text
;
242 // Validate creation using fallback values
243 switch ( property
) {
251 context
.config
[ property
] = value
;
254 context
.config
[ property
] = value
;
255 // Update suggestions
256 if ( context
.data
!== undefined ) {
257 if ( context
.data
.$textbox
.val().length
=== 0 ) {
258 // Hide the div when no suggestion exist
259 $.suggestions
.hide( context
);
261 // Rebuild the suggestions list
262 context
.data
.$container
.show();
263 // Update the size and position of the list
265 top
: context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
267 width
: context
.config
.$region
.outerWidth(),
271 // Process expandFrom, after this it is set to left or right.
272 context
.config
.expandFrom
= ( function ( expandFrom
) {
273 var regionWidth
, docWidth
, regionCenter
, docCenter
,
274 docDir
= $( document
.documentElement
).css( 'direction' ),
275 $region
= context
.config
.$region
;
277 // Backwards compatible
278 if ( context
.config
.positionFromLeft
) {
281 // Catch invalid values, default to 'auto'
282 } else if ( $.inArray( expandFrom
, [ 'left', 'right', 'start', 'end', 'auto' ] ) === -1 ) {
286 if ( expandFrom
=== 'auto' ) {
287 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
288 // If the markup explicitly contains a direction, use it.
289 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
291 regionWidth
= $region
.outerWidth();
292 docWidth
= $( document
).width();
293 if ( regionWidth
> ( 0.85 * docWidth
) ) {
294 // If the input size takes up more than 85% of the document horizontally
295 // expand the suggestions to the writing direction's native end.
296 expandFrom
= 'start';
298 // Calculate the center points of the input and document
299 regionCenter
= $region
.offset().left
+ regionWidth
/ 2;
300 docCenter
= docWidth
/ 2;
301 if ( Math
.abs( regionCenter
- docCenter
) < ( 0.10 * docCenter
) ) {
302 // If the input's center is within 10% of the document center
303 // use the writing direction's native end.
304 expandFrom
= 'start';
306 // Otherwise expand the input from the closest side of the page,
307 // towards the side of the page with the most free open space
308 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
314 if ( expandFrom
=== 'start' ) {
315 expandFrom
= docDir
=== 'rtl' ? 'right' : 'left';
317 } else if ( expandFrom
=== 'end' ) {
318 expandFrom
= docDir
=== 'rtl' ? 'left' : 'right';
323 }( context
.config
.expandFrom
) );
325 if ( context
.config
.expandFrom
=== 'left' ) {
327 newCSS
.left
= context
.config
.$region
.offset().left
;
328 newCSS
.right
= 'auto';
331 newCSS
.left
= 'auto';
332 newCSS
.right
= $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
335 context
.data
.$container
.css( newCSS
);
336 $results
= context
.data
.$container
.children( '.suggestions-results' );
339 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
340 /*jshint loopfunc:true */
341 text
= context
.config
.suggestions
[ i
];
342 $result
= $( '<div>' )
343 .addClass( 'suggestions-result' )
345 .data( 'text', context
.config
.suggestions
[ i
] )
346 .mousemove( function () {
347 context
.data
.selectedWithMouse
= true;
348 $.suggestions
.highlight(
350 $( this ).closest( '.suggestions-results .suggestions-result' ),
354 .appendTo( $results
);
355 // Allow custom rendering
356 if ( typeof context
.config
.result
.render
=== 'function' ) {
357 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[ i
], context
);
359 $result
.text( text
);
362 if ( context
.config
.highlightInput
) {
363 $result
.highlightText( context
.data
.prevText
);
366 // Widen results box if needed (new width is only calculated here, applied later).
368 // The monstrosity below accomplishes two things:
369 // * Wraps the text contents in a DOM element, so that we can know its width. There is
370 // no way to directly access the width of a text node, and we can't use the parent
371 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
372 // it, which trims it to a smaller width.
373 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
374 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
375 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
376 // still report the "trimmed" width. This should not be done in regular CSS
377 // stylesheets as we don't want this rule to apply to other <span> elements, like
378 // the ones generated by jquery.highlightText.
379 $spanForWidth
= $result
.wrapInner( '<span>' ).children();
380 childrenWidth
= $spanForWidth
.css( 'position', 'absolute' ).outerWidth();
381 $spanForWidth
.contents().unwrap();
383 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
384 // factor in any padding, margin, or border space on the parent
385 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
389 // Apply new width for results box, if any
390 if ( expWidth
> context
.data
.$container
.width() ) {
391 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
392 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
398 context
.config
[ property
] = Math
.max( 1, Math
.min( 100, value
) );
401 context
.config
[ property
] = Math
.max( 0, Math
.min( 1200, value
) );
404 context
.config
[ property
] = Math
.max( 1, value
);
406 case 'maxExpandFactor':
407 context
.config
[ property
] = Math
.max( 1, value
);
410 case 'submitOnClick':
411 case 'positionFromLeft':
412 case 'highlightInput':
413 context
.config
[ property
] = !!value
;
419 * Highlight a result in the results table
421 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
422 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
424 highlight: function ( context
, result
, updateTextbox
) {
425 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
426 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
427 if ( result
=== 'prev' ) {
428 if ( selected
.hasClass( 'suggestions-special' ) ) {
429 result
= context
.data
.$container
.find( '.suggestions-result:last' );
431 result
= selected
.prev();
432 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
433 // there is something in the DOM between selected element and the wrapper, bypass it
434 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
437 if ( selected
.length
=== 0 ) {
438 // we are at the beginning, so lets jump to the last item
439 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
440 result
= context
.data
.$container
.find( '.suggestions-special' );
442 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:last' );
446 } else if ( result
=== 'next' ) {
447 if ( selected
.length
=== 0 ) {
448 // No item selected, go to the first one
449 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:first' );
450 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
451 // No suggestion exists, go to the special one directly
452 result
= context
.data
.$container
.find( '.suggestions-special' );
455 result
= selected
.next();
456 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
457 // there is something in the DOM between selected element and the wrapper, bypass it
458 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
461 if ( selected
.hasClass( 'suggestions-special' ) ) {
464 result
.length
=== 0 &&
465 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
467 // We were at the last item, jump to the specials!
468 result
= context
.data
.$container
.find( '.suggestions-special' );
472 selected
.removeClass( 'suggestions-result-current' );
473 result
.addClass( 'suggestions-result-current' );
475 if ( updateTextbox
) {
476 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
477 $.suggestions
.restore( context
);
479 context
.data
.$textbox
.val( result
.data( 'text' ) );
480 // .val() doesn't call any event handlers, so
481 // let the world know what happened
482 context
.data
.$textbox
.change();
484 context
.data
.$textbox
.trigger( 'change' );
489 * Respond to keypress event
491 * @param {number} key Code of key pressed
493 keypress: function ( e
, context
, key
) {
495 wasVisible
= context
.data
.$container
.is( ':visible' ),
496 preventDefault
= false;
502 $.suggestions
.highlight( context
, 'next', true );
503 context
.data
.selectedWithMouse
= false;
505 $.suggestions
.update( context
, false );
507 preventDefault
= true;
512 $.suggestions
.highlight( context
, 'prev', true );
513 context
.data
.selectedWithMouse
= false;
515 preventDefault
= wasVisible
;
519 $.suggestions
.hide( context
);
520 $.suggestions
.restore( context
);
521 $.suggestions
.cancel( context
);
522 context
.data
.$textbox
.trigger( 'change' );
523 preventDefault
= wasVisible
;
527 preventDefault
= wasVisible
;
528 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
529 $.suggestions
.hide( context
);
530 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
531 // If nothing is selected or if something was selected with the mouse
532 // cancel any current requests and allow the form to be submitted
533 // (simply don't prevent default behavior).
534 $.suggestions
.cancel( context
);
535 preventDefault
= false;
536 } else if ( selected
.is( '.suggestions-special' ) ) {
537 if ( typeof context
.config
.special
.select
=== 'function' ) {
538 // Allow the callback to decide whether to prevent default or not
539 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
) === true ) {
540 preventDefault
= false;
544 if ( typeof context
.config
.result
.select
=== 'function' ) {
545 // Allow the callback to decide whether to prevent default or not
546 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
) === true ) {
547 preventDefault
= false;
553 $.suggestions
.update( context
, true );
556 if ( preventDefault
) {
563 // See file header for method documentation
564 $.fn
.suggestions = function () {
566 // Multi-context fields
570 $( this ).each( function () {
573 /* Construction and Loading */
575 context
= $( this ).data( 'suggestions-context' );
576 if ( context
=== undefined || context
=== null ) {
579 fetch: function () {},
580 cancel: function () {},
590 submitOnClick
: false,
593 highlightInput
: false
600 // Handle various calling styles
601 if ( args
.length
> 0 ) {
602 if ( typeof args
[ 0 ] === 'object' ) {
603 // Apply set of properties
604 for ( key
in args
[ 0 ] ) {
605 $.suggestions
.configure( context
, key
, args
[ 0 ][ key
] );
607 } else if ( typeof args
[ 0 ] === 'string' ) {
608 if ( args
.length
> 1 ) {
609 // Set property values
610 $.suggestions
.configure( context
, args
[ 0 ], args
[ 1 ] );
611 } else if ( returnValue
=== null || returnValue
=== undefined ) {
612 // Get property values, but don't give access to internal data - returns only the first
613 returnValue
= ( args
[ 0 ] in context
.config
? undefined : context
.config
[ args
[ 0 ] ] );
620 if ( context
.data
=== undefined ) {
622 // ID of running timer
625 // Text in textbox when suggestions were last fetched
628 // Cache of fetched suggestions
631 // Number of results visible without scrolling
634 // Suggestion the last mousedown event occurred on
635 mouseDownOn
: $( [] ),
637 selectedWithMouse
: false
640 context
.data
.$container
= $( '<div>' )
641 .css( 'display', 'none' )
642 .addClass( 'suggestions' )
644 $( '<div>' ).addClass( 'suggestions-results' )
645 // Can't use click() because the container div is hidden when the
646 // textbox loses focus. Instead, listen for a mousedown followed
647 // by a mouseup on the same div.
648 .mousedown( function ( e
) {
649 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
651 .mouseup( function ( e
) {
652 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
653 $other
= context
.data
.mouseDownOn
;
655 context
.data
.mouseDownOn
= $( [] );
656 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
659 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
660 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
661 $.suggestions
.highlight( context
, $result
, true );
662 if ( typeof context
.config
.result
.select
=== 'function' ) {
663 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
);
665 // This will hide the link we're just clicking on, which causes problems
666 // when done synchronously in at least Firefox 3.6 (bug 62858).
667 setTimeout( function () {
668 $.suggestions
.hide( context
);
671 // Always bring focus to the textbox, as that's probably where the user expects it
672 // if they were just typing.
673 context
.data
.$textbox
.focus();
677 $( '<div>' ).addClass( 'suggestions-special' )
678 // Can't use click() because the container div is hidden when the
679 // textbox loses focus. Instead, listen for a mousedown followed
680 // by a mouseup on the same div.
681 .mousedown( function ( e
) {
682 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
684 .mouseup( function ( e
) {
685 var $special
= $( e
.target
).closest( '.suggestions-special' ),
686 $other
= context
.data
.mouseDownOn
;
688 context
.data
.mouseDownOn
= $( [] );
689 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
692 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
693 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
694 if ( typeof context
.config
.special
.select
=== 'function' ) {
695 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
);
697 // This will hide the link we're just clicking on, which causes problems
698 // when done synchronously in at least Firefox 3.6 (bug 62858).
699 setTimeout( function () {
700 $.suggestions
.hide( context
);
703 // Always bring focus to the textbox, as that's probably where the user expects it
704 // if they were just typing.
705 context
.data
.$textbox
.focus();
707 .mousemove( function ( e
) {
708 context
.data
.selectedWithMouse
= true;
709 $.suggestions
.highlight(
710 context
, $( e
.target
).closest( '.suggestions-special' ), false
714 .appendTo( $( 'body' ) );
717 // Stop browser autocomplete from interfering
718 .attr( 'autocomplete', 'off' )
719 .keydown( function ( e
) {
720 // Store key pressed to handle later
721 context
.data
.keypressed
= e
.which
;
722 context
.data
.keypressedCount
= 0;
724 .keypress( function ( e
) {
725 context
.data
.keypressedCount
++;
726 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
728 .keyup( function ( e
) {
729 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
730 // keypress in between, solve it
731 if ( context
.data
.keypressedCount
=== 0 ) {
732 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
736 // When losing focus because of a mousedown
737 // on a suggestion, don't hide the suggestions
738 if ( context
.data
.mouseDownOn
.length
> 0 ) {
741 $.suggestions
.hide( context
);
742 $.suggestions
.cancel( context
);
746 // Store the context for next time
747 $( this ).data( 'suggestions-context', context
);
749 return returnValue
!== undefined ? returnValue
: $( this );
754 * @mixins jQuery.plugin.suggestions