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.
145 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
147 update: function ( context
, delayed
) {
148 function maybeFetch() {
149 var val
= context
.data
.$textbox
.val(),
150 cache
= context
.data
.cache
,
153 if ( typeof context
.config
.update
.before
=== 'function' ) {
154 context
.config
.update
.before
.call( context
.data
.$textbox
);
157 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
158 // if the textbox is empty then clear the result div, but leave other settings intouched
159 if ( val
.length
=== 0 ) {
160 $.suggestions
.hide( context
);
161 context
.data
.prevText
= '';
163 val
!== context
.data
.prevText
||
164 !context
.data
.$container
.is( ':visible' )
166 context
.data
.prevText
= val
;
168 if ( context
.config
.cache
&& hasOwn
.call( cache
, val
) ) {
169 if ( +new Date() - cache
[ val
].timestamp
< context
.config
.cacheMaxAge
) {
170 context
.data
.$textbox
.suggestions( 'suggestions', cache
[ val
].suggestions
);
171 if ( typeof context
.config
.update
.after
=== 'function' ) {
172 context
.config
.update
.after
.call( context
.data
.$textbox
);
180 if ( !cacheHit
&& typeof context
.config
.fetch
=== 'function' ) {
181 context
.config
.fetch
.call(
182 context
.data
.$textbox
,
184 function ( suggestions
) {
185 suggestions
= suggestions
.slice( 0, context
.config
.maxRows
);
186 context
.data
.$textbox
.suggestions( 'suggestions', suggestions
);
187 if ( typeof context
.config
.update
.after
=== 'function' ) {
188 context
.config
.update
.after
.call( context
.data
.$textbox
);
190 if ( context
.config
.cache
) {
192 suggestions
: suggestions
,
193 timestamp
: +new Date()
197 context
.config
.maxRows
202 // Always update special rendering
203 $.suggestions
.special( context
);
206 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
207 $.suggestions
.cancel( context
);
210 // To avoid many started/aborted requests while typing, we're gonna take a short
211 // break before trying to fetch data.
212 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
218 special: function ( context
) {
219 // Allow custom rendering - but otherwise don't do any rendering
220 if ( typeof context
.config
.special
.render
=== 'function' ) {
221 // Wait for the browser to update the value
222 setTimeout( function () {
224 var $special
= context
.data
.$container
.find( '.suggestions-special' );
225 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val(), context
);
231 * Sets the value of a property, and updates the widget accordingly
232 * @param {string} property Name of property
233 * @param {Mixed} value Value to set property with
235 configure: function ( context
, property
, value
) {
237 $result
, $results
, $spanForWidth
, childrenWidth
,
238 i
, expWidth
, maxWidth
, text
;
240 // Validate creation using fallback values
241 switch ( property
) {
249 context
.config
[property
] = value
;
252 context
.config
[property
] = value
;
253 // Update suggestions
254 if ( context
.data
!== undefined ) {
255 if ( context
.data
.$textbox
.val().length
=== 0 ) {
256 // Hide the div when no suggestion exist
257 $.suggestions
.hide( context
);
259 // Rebuild the suggestions list
260 context
.data
.$container
.show();
261 // Update the size and position of the list
263 top
: context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
265 width
: context
.config
.$region
.outerWidth(),
269 // Process expandFrom, after this it is set to left or right.
270 context
.config
.expandFrom
= ( function ( expandFrom
) {
271 var regionWidth
, docWidth
, regionCenter
, docCenter
,
272 docDir
= $( document
.documentElement
).css( 'direction' ),
273 $region
= context
.config
.$region
;
275 // Backwards compatible
276 if ( context
.config
.positionFromLeft
) {
279 // Catch invalid values, default to 'auto'
280 } else if ( $.inArray( expandFrom
, ['left', 'right', 'start', 'end', 'auto'] ) === -1 ) {
284 if ( expandFrom
=== 'auto' ) {
285 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
286 // If the markup explicitly contains a direction, use it.
287 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
289 regionWidth
= $region
.outerWidth();
290 docWidth
= $( document
).width();
291 if ( regionWidth
> ( 0.85 * docWidth
) ) {
292 // If the input size takes up more than 85% of the document horizontally
293 // expand the suggestions to the writing direction's native end.
294 expandFrom
= 'start';
296 // Calculate the center points of the input and document
297 regionCenter
= $region
.offset().left
+ regionWidth
/ 2;
298 docCenter
= docWidth
/ 2;
299 if ( Math
.abs( regionCenter
- docCenter
) < ( 0.10 * docCenter
) ) {
300 // If the input's center is within 10% of the document center
301 // use the writing direction's native end.
302 expandFrom
= 'start';
304 // Otherwise expand the input from the closest side of the page,
305 // towards the side of the page with the most free open space
306 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
312 if ( expandFrom
=== 'start' ) {
313 expandFrom
= docDir
=== 'rtl' ? 'right' : 'left';
315 } else if ( expandFrom
=== 'end' ) {
316 expandFrom
= docDir
=== 'rtl' ? 'left' : 'right';
321 }( context
.config
.expandFrom
) );
323 if ( context
.config
.expandFrom
=== 'left' ) {
325 newCSS
.left
= context
.config
.$region
.offset().left
;
326 newCSS
.right
= 'auto';
329 newCSS
.left
= 'auto';
330 newCSS
.right
= $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
333 context
.data
.$container
.css( newCSS
);
334 $results
= context
.data
.$container
.children( '.suggestions-results' );
337 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
338 /*jshint loopfunc:true */
339 text
= context
.config
.suggestions
[i
];
340 $result
= $( '<div>' )
341 .addClass( 'suggestions-result' )
343 .data( 'text', context
.config
.suggestions
[i
] )
344 .mousemove( function () {
345 context
.data
.selectedWithMouse
= true;
346 $.suggestions
.highlight(
348 $( this ).closest( '.suggestions-results .suggestions-result' ),
352 .appendTo( $results
);
353 // Allow custom rendering
354 if ( typeof context
.config
.result
.render
=== 'function' ) {
355 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[i
], context
);
357 $result
.text( text
);
360 if ( context
.config
.highlightInput
) {
361 $result
.highlightText( context
.data
.prevText
);
364 // Widen results box if needed (new width is only calculated here, applied later).
366 // The monstrosity below accomplishes two things:
367 // * Wraps the text contents in a DOM element, so that we can know its width. There is
368 // no way to directly access the width of a text node, and we can't use the parent
369 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
370 // it, which trims it to a smaller width.
371 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
372 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
373 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
374 // still report the "trimmed" width. This should not be done in regular CSS
375 // stylesheets as we don't want this rule to apply to other <span> elements, like
376 // the ones generated by jquery.highlightText.
377 $spanForWidth
= $result
.wrapInner( '<span>' ).children();
378 childrenWidth
= $spanForWidth
.css( 'position', 'absolute' ).outerWidth();
379 $spanForWidth
.contents().unwrap();
381 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
382 // factor in any padding, margin, or border space on the parent
383 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
387 // Apply new width for results box, if any
388 if ( expWidth
> context
.data
.$container
.width() ) {
389 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
390 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
396 context
.config
[property
] = Math
.max( 1, Math
.min( 100, value
) );
399 context
.config
[property
] = Math
.max( 0, Math
.min( 1200, value
) );
402 context
.config
[property
] = Math
.max( 1, value
);
404 case 'maxExpandFactor':
405 context
.config
[property
] = Math
.max( 1, value
);
408 case 'submitOnClick':
409 case 'positionFromLeft':
410 case 'highlightInput':
411 context
.config
[property
] = !!value
;
417 * Highlight a result in the results table
418 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
419 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
421 highlight: function ( context
, result
, updateTextbox
) {
422 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
423 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
424 if ( result
=== 'prev' ) {
425 if ( selected
.hasClass( 'suggestions-special' ) ) {
426 result
= context
.data
.$container
.find( '.suggestions-result:last' );
428 result
= selected
.prev();
429 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
430 // there is something in the DOM between selected element and the wrapper, bypass it
431 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
434 if ( selected
.length
=== 0 ) {
435 // we are at the beginning, so lets jump to the last item
436 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
437 result
= context
.data
.$container
.find( '.suggestions-special' );
439 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:last' );
443 } else if ( result
=== 'next' ) {
444 if ( selected
.length
=== 0 ) {
445 // No item selected, go to the first one
446 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:first' );
447 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
448 // No suggestion exists, go to the special one directly
449 result
= context
.data
.$container
.find( '.suggestions-special' );
452 result
= selected
.next();
453 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
454 // there is something in the DOM between selected element and the wrapper, bypass it
455 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
458 if ( selected
.hasClass( 'suggestions-special' ) ) {
461 result
.length
=== 0 &&
462 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
464 // We were at the last item, jump to the specials!
465 result
= context
.data
.$container
.find( '.suggestions-special' );
469 selected
.removeClass( 'suggestions-result-current' );
470 result
.addClass( 'suggestions-result-current' );
472 if ( updateTextbox
) {
473 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
474 $.suggestions
.restore( context
);
476 context
.data
.$textbox
.val( result
.data( 'text' ) );
477 // .val() doesn't call any event handlers, so
478 // let the world know what happened
479 context
.data
.$textbox
.change();
481 context
.data
.$textbox
.trigger( 'change' );
486 * Respond to keypress event
487 * @param {number} key Code of key pressed
489 keypress: function ( e
, context
, key
) {
491 wasVisible
= context
.data
.$container
.is( ':visible' ),
492 preventDefault
= false;
498 $.suggestions
.highlight( context
, 'next', true );
499 context
.data
.selectedWithMouse
= false;
501 $.suggestions
.update( context
, false );
503 preventDefault
= true;
508 $.suggestions
.highlight( context
, 'prev', true );
509 context
.data
.selectedWithMouse
= false;
511 preventDefault
= wasVisible
;
515 $.suggestions
.hide( context
);
516 $.suggestions
.restore( context
);
517 $.suggestions
.cancel( context
);
518 context
.data
.$textbox
.trigger( 'change' );
519 preventDefault
= wasVisible
;
523 preventDefault
= wasVisible
;
524 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
525 $.suggestions
.hide( context
);
526 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
527 // If nothing is selected or if something was selected with the mouse
528 // cancel any current requests and allow the form to be submitted
529 // (simply don't prevent default behavior).
530 $.suggestions
.cancel( context
);
531 preventDefault
= false;
532 } else if ( selected
.is( '.suggestions-special' ) ) {
533 if ( typeof context
.config
.special
.select
=== 'function' ) {
534 // Allow the callback to decide whether to prevent default or not
535 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
) === true ) {
536 preventDefault
= false;
540 if ( typeof context
.config
.result
.select
=== 'function' ) {
541 // Allow the callback to decide whether to prevent default or not
542 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
) === true ) {
543 preventDefault
= false;
549 $.suggestions
.update( context
, true );
552 if ( preventDefault
) {
559 // See file header for method documentation
560 $.fn
.suggestions = function () {
562 // Multi-context fields
566 $( this ).each( function () {
569 /* Construction and Loading */
571 context
= $( this ).data( 'suggestions-context' );
572 if ( context
=== undefined || context
=== null ) {
575 fetch: function () {},
576 cancel: function () {},
586 submitOnClick
: false,
589 highlightInput
: false
596 // Handle various calling styles
597 if ( args
.length
> 0 ) {
598 if ( typeof args
[0] === 'object' ) {
599 // Apply set of properties
600 for ( key
in args
[0] ) {
601 $.suggestions
.configure( context
, key
, args
[0][key
] );
603 } else if ( typeof args
[0] === 'string' ) {
604 if ( args
.length
> 1 ) {
605 // Set property values
606 $.suggestions
.configure( context
, args
[0], args
[1] );
607 } else if ( returnValue
=== null || returnValue
=== undefined ) {
608 // Get property values, but don't give access to internal data - returns only the first
609 returnValue
= ( args
[0] in context
.config
? undefined : context
.config
[args
[0]] );
616 if ( context
.data
=== undefined ) {
618 // ID of running timer
621 // Text in textbox when suggestions were last fetched
624 // Cache of fetched suggestions
627 // Number of results visible without scrolling
630 // Suggestion the last mousedown event occurred on
631 mouseDownOn
: $( [] ),
633 selectedWithMouse
: false
636 context
.data
.$container
= $( '<div>' )
637 .css( 'display', 'none' )
638 .addClass( 'suggestions' )
640 $( '<div>' ).addClass( 'suggestions-results' )
641 // Can't use click() because the container div is hidden when the
642 // textbox loses focus. Instead, listen for a mousedown followed
643 // by a mouseup on the same div.
644 .mousedown( function ( e
) {
645 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
647 .mouseup( function ( e
) {
648 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
649 $other
= context
.data
.mouseDownOn
;
651 context
.data
.mouseDownOn
= $( [] );
652 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
655 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
656 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
657 $.suggestions
.highlight( context
, $result
, true );
658 if ( typeof context
.config
.result
.select
=== 'function' ) {
659 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
);
661 // This will hide the link we're just clicking on, which causes problems
662 // when done synchronously in at least Firefox 3.6 (bug 62858).
663 setTimeout( function () {
664 $.suggestions
.hide( context
);
667 // Always bring focus to the textbox, as that's probably where the user expects it
668 // if they were just typing.
669 context
.data
.$textbox
.focus();
673 $( '<div>' ).addClass( 'suggestions-special' )
674 // Can't use click() because the container div is hidden when the
675 // textbox loses focus. Instead, listen for a mousedown followed
676 // by a mouseup on the same div.
677 .mousedown( function ( e
) {
678 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
680 .mouseup( function ( e
) {
681 var $special
= $( e
.target
).closest( '.suggestions-special' ),
682 $other
= context
.data
.mouseDownOn
;
684 context
.data
.mouseDownOn
= $( [] );
685 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
688 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
689 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
690 if ( typeof context
.config
.special
.select
=== 'function' ) {
691 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
);
693 // This will hide the link we're just clicking on, which causes problems
694 // when done synchronously in at least Firefox 3.6 (bug 62858).
695 setTimeout( function () {
696 $.suggestions
.hide( context
);
699 // Always bring focus to the textbox, as that's probably where the user expects it
700 // if they were just typing.
701 context
.data
.$textbox
.focus();
703 .mousemove( function ( e
) {
704 context
.data
.selectedWithMouse
= true;
705 $.suggestions
.highlight(
706 context
, $( e
.target
).closest( '.suggestions-special' ), false
710 .appendTo( $( 'body' ) );
713 // Stop browser autocomplete from interfering
714 .attr( 'autocomplete', 'off' )
715 .keydown( function ( e
) {
716 // Store key pressed to handle later
717 context
.data
.keypressed
= e
.which
;
718 context
.data
.keypressedCount
= 0;
720 .keypress( function ( e
) {
721 context
.data
.keypressedCount
++;
722 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
724 .keyup( function ( e
) {
725 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
726 // keypress in between, solve it
727 if ( context
.data
.keypressedCount
=== 0 ) {
728 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
732 // When losing focus because of a mousedown
733 // on a suggestion, don't hide the suggestions
734 if ( context
.data
.mouseDownOn
.length
> 0 ) {
737 $.suggestions
.hide( context
);
738 $.suggestions
.cancel( context
);
742 // Store the context for next time
743 $( this ).data( 'suggestions-context', context
);
745 return returnValue
!== undefined ? returnValue
: $( this );
750 * @mixins jQuery.plugin.suggestions