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 {jQuery} [options.$region=this] The element to place the suggestions below and match width of.
58 * @param {string[]} [options.suggestions] Array of suggestions to display.
60 * @param {number} [options.maxRows=10] Maximum number of suggestions to display at one time.
61 * Must be between 1 and 100.
63 * @param {number} [options.delay=120] Number of milliseconds to wait for the user to stop typing.
64 * Must be between 0 and 1200.
66 * @param {boolean} [options.cache=false] Whether to cache results from a fetch.
68 * @param {number} [options.cacheMaxAge=60000] Number of milliseconds to cache results from a fetch.
69 * Must be higher than 1. Defaults to 1 minute.
71 * @param {boolean} [options.submitOnClick=false] Whether to submit the form containing the textbox
72 * when a suggestion is clicked.
74 * @param {number} [options.maxExpandFactor=3] Maximum suggestions box width relative to the textbox
75 * width. If set to e.g. 2, the suggestions box will never be grown beyond 2 times the width of
76 * the textbox. Must be higher than 1.
78 * @param {string} [options.expandFrom=auto] Which direction to offset the suggestion box from.
79 * Values 'start' and 'end' translate to left and right respectively depending on the directionality
80 * of the current document, according to `$( 'html' ).css( 'direction' )`.
81 * Valid values: "left", "right", "start", "end", and "auto".
83 * @param {boolean} [options.positionFromLeft] Sets `expandFrom=left`, for backwards
86 * @param {boolean} [options.highlightInput=false] Whether to hightlight matched portions of the
91 var hasOwn
= Object
.hasOwnProperty
;
94 * Used by jQuery.plugin.suggestions.
96 * @class jQuery.suggestions
102 * Cancel any delayed maybeFetch() call and callback the context so
103 * they can cancel any async fetching if they use AJAX or something.
105 cancel: function ( context
) {
106 if ( context
.data
.timerID
!== null ) {
107 clearTimeout( context
.data
.timerID
);
109 if ( $.isFunction( context
.config
.cancel
) ) {
110 context
.config
.cancel
.call( context
.data
.$textbox
);
115 * Hide the element with suggestions and clean up some state.
117 hide: function ( context
) {
118 // Remove any highlights, including on "special" items
119 context
.data
.$container
.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
120 // Hide the container
121 context
.data
.$container
.hide();
125 * Restore the text the user originally typed in the textbox, before it
126 * was overwritten by highlight(). This restores the value the currently
127 * displayed suggestions are based on, rather than the value just before
128 * highlight() overwrote it; the former is arguably slightly more sensible.
130 restore: function ( context
) {
131 context
.data
.$textbox
.val( context
.data
.prevText
);
135 * Ask the user-specified callback for new suggestions. Any previous delayed
136 * call to this function still pending will be canceled. If the value in the
137 * textbox is empty or hasn't changed since the last time suggestions were fetched,
138 * this function does nothing.
139 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
141 update: function ( context
, delayed
) {
142 function maybeFetch() {
143 var val
= context
.data
.$textbox
.val(),
144 cache
= context
.data
.cache
,
147 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
148 // if the textbox is empty then clear the result div, but leave other settings intouched
149 if ( val
.length
=== 0 ) {
150 $.suggestions
.hide( context
);
151 context
.data
.prevText
= '';
153 val
!== context
.data
.prevText
||
154 !context
.data
.$container
.is( ':visible' )
156 context
.data
.prevText
= val
;
158 if ( context
.config
.cache
&& hasOwn
.call( cache
, val
) ) {
159 if ( +new Date() - cache
[ val
].timestamp
< context
.config
.cacheMaxAge
) {
160 context
.data
.$textbox
.suggestions( 'suggestions', cache
[ val
].suggestions
);
167 if ( !cacheHit
&& typeof context
.config
.fetch
=== 'function' ) {
168 context
.config
.fetch
.call(
169 context
.data
.$textbox
,
171 function ( suggestions
) {
172 suggestions
= suggestions
.slice( 0, context
.config
.maxRows
);
173 context
.data
.$textbox
.suggestions( 'suggestions', suggestions
);
174 if ( context
.config
.cache
) {
176 suggestions
: suggestions
,
177 timestamp
: +new Date()
181 context
.config
.maxRows
186 // Always update special rendering
187 $.suggestions
.special( context
);
190 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
191 $.suggestions
.cancel( context
);
194 // To avoid many started/aborted requests while typing, we're gonna take a short
195 // break before trying to fetch data.
196 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
202 special: function ( context
) {
203 // Allow custom rendering - but otherwise don't do any rendering
204 if ( typeof context
.config
.special
.render
=== 'function' ) {
205 // Wait for the browser to update the value
206 setTimeout( function () {
208 var $special
= context
.data
.$container
.find( '.suggestions-special' );
209 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val(), context
);
215 * Sets the value of a property, and updates the widget accordingly
216 * @param {string} property Name of property
217 * @param {Mixed} value Value to set property with
219 configure: function ( context
, property
, value
) {
221 $result
, $results
, $spanForWidth
, childrenWidth
,
222 i
, expWidth
, maxWidth
, text
;
224 // Validate creation using fallback values
225 switch ( property
) {
232 context
.config
[property
] = value
;
235 context
.config
[property
] = value
;
236 // Update suggestions
237 if ( context
.data
!== undefined ) {
238 if ( context
.data
.$textbox
.val().length
=== 0 ) {
239 // Hide the div when no suggestion exist
240 $.suggestions
.hide( context
);
242 // Rebuild the suggestions list
243 context
.data
.$container
.show();
244 // Update the size and position of the list
246 top
: context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
248 width
: context
.config
.$region
.outerWidth(),
252 // Process expandFrom, after this it is set to left or right.
253 context
.config
.expandFrom
= ( function ( expandFrom
) {
254 var regionWidth
, docWidth
, regionCenter
, docCenter
,
255 docDir
= $( document
.documentElement
).css( 'direction' ),
256 $region
= context
.config
.$region
;
258 // Backwards compatible
259 if ( context
.config
.positionFromLeft
) {
262 // Catch invalid values, default to 'auto'
263 } else if ( $.inArray( expandFrom
, ['left', 'right', 'start', 'end', 'auto'] ) === -1 ) {
267 if ( expandFrom
=== 'auto' ) {
268 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
269 // If the markup explicitly contains a direction, use it.
270 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
272 regionWidth
= $region
.outerWidth();
273 docWidth
= $( document
).width();
274 if ( regionWidth
> ( 0.85 * docWidth
) ) {
275 // If the input size takes up more than 85% of the document horizontally
276 // expand the suggestions to the writing direction's native end.
277 expandFrom
= 'start';
279 // Calculate the center points of the input and document
280 regionCenter
= $region
.offset().left
+ regionWidth
/ 2;
281 docCenter
= docWidth
/ 2;
282 if ( Math
.abs( regionCenter
- docCenter
) < ( 0.10 * docCenter
) ) {
283 // If the input's center is within 10% of the document center
284 // use the writing direction's native end.
285 expandFrom
= 'start';
287 // Otherwise expand the input from the closest side of the page,
288 // towards the side of the page with the most free open space
289 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
295 if ( expandFrom
=== 'start' ) {
296 expandFrom
= docDir
=== 'rtl' ? 'right' : 'left';
298 } else if ( expandFrom
=== 'end' ) {
299 expandFrom
= docDir
=== 'rtl' ? 'left' : 'right';
304 }( context
.config
.expandFrom
) );
306 if ( context
.config
.expandFrom
=== 'left' ) {
308 newCSS
.left
= context
.config
.$region
.offset().left
;
309 newCSS
.right
= 'auto';
312 newCSS
.left
= 'auto';
313 newCSS
.right
= $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
316 context
.data
.$container
.css( newCSS
);
317 $results
= context
.data
.$container
.children( '.suggestions-results' );
320 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
321 /*jshint loopfunc:true */
322 text
= context
.config
.suggestions
[i
];
323 $result
= $( '<div>' )
324 .addClass( 'suggestions-result' )
326 .data( 'text', context
.config
.suggestions
[i
] )
327 .mousemove( function () {
328 context
.data
.selectedWithMouse
= true;
329 $.suggestions
.highlight(
331 $( this ).closest( '.suggestions-results .suggestions-result' ),
335 .appendTo( $results
);
336 // Allow custom rendering
337 if ( typeof context
.config
.result
.render
=== 'function' ) {
338 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[i
], context
);
340 $result
.text( text
);
343 if ( context
.config
.highlightInput
) {
344 $result
.highlightText( context
.data
.prevText
);
347 // Widen results box if needed (new width is only calculated here, applied later).
349 // The monstrosity below accomplishes two things:
350 // * Wraps the text contents in a DOM element, so that we can know its width. There is
351 // no way to directly access the width of a text node, and we can't use the parent
352 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
353 // it, which trims it to a smaller width.
354 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
355 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
356 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
357 // still report the "trimmed" width. This should not be done in regular CSS
358 // stylesheets as we don't want this rule to apply to other <span> elements, like
359 // the ones generated by jquery.highlightText.
360 $spanForWidth
= $result
.wrapInner( '<span>' ).children();
361 childrenWidth
= $spanForWidth
.css( 'position', 'absolute' ).outerWidth();
362 $spanForWidth
.contents().unwrap();
364 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
365 // factor in any padding, margin, or border space on the parent
366 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
370 // Apply new width for results box, if any
371 if ( expWidth
> context
.data
.$container
.width() ) {
372 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
373 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
379 context
.config
[property
] = Math
.max( 1, Math
.min( 100, value
) );
382 context
.config
[property
] = Math
.max( 0, Math
.min( 1200, value
) );
385 context
.config
[property
] = Math
.max( 1, value
);
387 case 'maxExpandFactor':
388 context
.config
[property
] = Math
.max( 1, value
);
391 case 'submitOnClick':
392 case 'positionFromLeft':
393 case 'highlightInput':
394 context
.config
[property
] = !!value
;
400 * Highlight a result in the results table
401 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
402 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
404 highlight: function ( context
, result
, updateTextbox
) {
405 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
406 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
407 if ( result
=== 'prev' ) {
408 if ( selected
.hasClass( 'suggestions-special' ) ) {
409 result
= context
.data
.$container
.find( '.suggestions-result:last' );
411 result
= selected
.prev();
412 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
413 // there is something in the DOM between selected element and the wrapper, bypass it
414 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
417 if ( selected
.length
=== 0 ) {
418 // we are at the beginning, so lets jump to the last item
419 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
420 result
= context
.data
.$container
.find( '.suggestions-special' );
422 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:last' );
426 } else if ( result
=== 'next' ) {
427 if ( selected
.length
=== 0 ) {
428 // No item selected, go to the first one
429 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:first' );
430 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
431 // No suggestion exists, go to the special one directly
432 result
= context
.data
.$container
.find( '.suggestions-special' );
435 result
= selected
.next();
436 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
437 // there is something in the DOM between selected element and the wrapper, bypass it
438 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
441 if ( selected
.hasClass( 'suggestions-special' ) ) {
444 result
.length
=== 0 &&
445 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
447 // We were at the last item, jump to the specials!
448 result
= context
.data
.$container
.find( '.suggestions-special' );
452 selected
.removeClass( 'suggestions-result-current' );
453 result
.addClass( 'suggestions-result-current' );
455 if ( updateTextbox
) {
456 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
457 $.suggestions
.restore( context
);
459 context
.data
.$textbox
.val( result
.data( 'text' ) );
460 // .val() doesn't call any event handlers, so
461 // let the world know what happened
462 context
.data
.$textbox
.change();
464 context
.data
.$textbox
.trigger( 'change' );
469 * Respond to keypress event
470 * @param {number} key Code of key pressed
472 keypress: function ( e
, context
, key
) {
474 wasVisible
= context
.data
.$container
.is( ':visible' ),
475 preventDefault
= false;
481 $.suggestions
.highlight( context
, 'next', true );
482 context
.data
.selectedWithMouse
= false;
484 $.suggestions
.update( context
, false );
486 preventDefault
= true;
491 $.suggestions
.highlight( context
, 'prev', true );
492 context
.data
.selectedWithMouse
= false;
494 preventDefault
= wasVisible
;
498 $.suggestions
.hide( context
);
499 $.suggestions
.restore( context
);
500 $.suggestions
.cancel( context
);
501 context
.data
.$textbox
.trigger( 'change' );
502 preventDefault
= wasVisible
;
506 preventDefault
= wasVisible
;
507 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
508 $.suggestions
.hide( context
);
509 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
510 // If nothing is selected or if something was selected with the mouse
511 // cancel any current requests and allow the form to be submitted
512 // (simply don't prevent default behavior).
513 $.suggestions
.cancel( context
);
514 preventDefault
= false;
515 } else if ( selected
.is( '.suggestions-special' ) ) {
516 if ( typeof context
.config
.special
.select
=== 'function' ) {
517 // Allow the callback to decide whether to prevent default or not
518 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
) === true ) {
519 preventDefault
= false;
523 if ( typeof context
.config
.result
.select
=== 'function' ) {
524 // Allow the callback to decide whether to prevent default or not
525 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
) === true ) {
526 preventDefault
= false;
532 $.suggestions
.update( context
, true );
535 if ( preventDefault
) {
542 // See file header for method documentation
543 $.fn
.suggestions = function () {
545 // Multi-context fields
549 $( this ).each( function () {
552 /* Construction and Loading */
554 context
= $( this ).data( 'suggestions-context' );
555 if ( context
=== undefined || context
=== null ) {
558 fetch: function () {},
559 cancel: function () {},
568 submitOnClick
: false,
571 highlightInput
: false
578 // Handle various calling styles
579 if ( args
.length
> 0 ) {
580 if ( typeof args
[0] === 'object' ) {
581 // Apply set of properties
582 for ( key
in args
[0] ) {
583 $.suggestions
.configure( context
, key
, args
[0][key
] );
585 } else if ( typeof args
[0] === 'string' ) {
586 if ( args
.length
> 1 ) {
587 // Set property values
588 $.suggestions
.configure( context
, args
[0], args
[1] );
589 } else if ( returnValue
=== null || returnValue
=== undefined ) {
590 // Get property values, but don't give access to internal data - returns only the first
591 returnValue
= ( args
[0] in context
.config
? undefined : context
.config
[args
[0]] );
598 if ( context
.data
=== undefined ) {
600 // ID of running timer
603 // Text in textbox when suggestions were last fetched
606 // Cache of fetched suggestions
609 // Number of results visible without scrolling
612 // Suggestion the last mousedown event occurred on
613 mouseDownOn
: $( [] ),
615 selectedWithMouse
: false
618 context
.data
.$container
= $( '<div>' )
619 .css( 'display', 'none' )
620 .addClass( 'suggestions' )
622 $( '<div>' ).addClass( 'suggestions-results' )
623 // Can't use click() because the container div is hidden when the
624 // textbox loses focus. Instead, listen for a mousedown followed
625 // by a mouseup on the same div.
626 .mousedown( function ( e
) {
627 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
629 .mouseup( function ( e
) {
630 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
631 $other
= context
.data
.mouseDownOn
;
633 context
.data
.mouseDownOn
= $( [] );
634 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
637 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
638 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
639 $.suggestions
.highlight( context
, $result
, true );
640 if ( typeof context
.config
.result
.select
=== 'function' ) {
641 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
);
643 // This will hide the link we're just clicking on, which causes problems
644 // when done synchronously in at least Firefox 3.6 (bug 62858).
645 setTimeout( function () {
646 $.suggestions
.hide( context
);
649 // Always bring focus to the textbox, as that's probably where the user expects it
650 // if they were just typing.
651 context
.data
.$textbox
.focus();
655 $( '<div>' ).addClass( 'suggestions-special' )
656 // Can't use click() because the container div is hidden when the
657 // textbox loses focus. Instead, listen for a mousedown followed
658 // by a mouseup on the same div.
659 .mousedown( function ( e
) {
660 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
662 .mouseup( function ( e
) {
663 var $special
= $( e
.target
).closest( '.suggestions-special' ),
664 $other
= context
.data
.mouseDownOn
;
666 context
.data
.mouseDownOn
= $( [] );
667 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
670 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
671 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
672 if ( typeof context
.config
.special
.select
=== 'function' ) {
673 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
);
675 // This will hide the link we're just clicking on, which causes problems
676 // when done synchronously in at least Firefox 3.6 (bug 62858).
677 setTimeout( function () {
678 $.suggestions
.hide( context
);
681 // Always bring focus to the textbox, as that's probably where the user expects it
682 // if they were just typing.
683 context
.data
.$textbox
.focus();
685 .mousemove( function ( e
) {
686 context
.data
.selectedWithMouse
= true;
687 $.suggestions
.highlight(
688 context
, $( e
.target
).closest( '.suggestions-special' ), false
692 .appendTo( $( 'body' ) );
695 // Stop browser autocomplete from interfering
696 .attr( 'autocomplete', 'off' )
697 .keydown( function ( e
) {
698 // Store key pressed to handle later
699 context
.data
.keypressed
= e
.which
;
700 context
.data
.keypressedCount
= 0;
702 .keypress( function ( e
) {
703 context
.data
.keypressedCount
++;
704 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
706 .keyup( function ( e
) {
707 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
708 // keypress in between, solve it
709 if ( context
.data
.keypressedCount
=== 0 ) {
710 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
714 // When losing focus because of a mousedown
715 // on a suggestion, don't hide the suggestions
716 if ( context
.data
.mouseDownOn
.length
> 0 ) {
719 $.suggestions
.hide( context
);
720 $.suggestions
.cancel( context
);
724 // Store the context for next time
725 $( this ).data( 'suggestions-context', context
);
727 return returnValue
!== undefined ? returnValue
: $( this );
732 * @mixins jQuery.plugin.suggestions