2 * This plugin provides a generic way to add suggestions to a text box.
7 * $( '#textbox' ).suggestions( { option1: value1, option2: value2 } );
8 * $( '#textbox' ).suggestions( option, value );
10 * value = $( '#textbox' ).suggestions( option );
12 * $( '#textbox' ).suggestions();
16 * fetch(query): Callback that should fetch suggestions and set the suggestions property.
17 * Executed in the context of the textbox
19 * cancel: Callback function to call when any pending asynchronous suggestions fetches
20 * should be canceled. Executed in the context of the textbox
22 * special: Set of callbacks for rendering and selecting
23 * Type: Object of Functions 'render' and 'select'
24 * result: Set of callbacks for rendering and selecting
25 * Type: Object of Functions 'render' and 'select'
26 * $region: jQuery selection of element to place the suggestions below and match width of
27 * Type: jQuery Object, Default: $( this )
28 * suggestions: Suggestions to display
29 * Type: Array of strings
30 * maxRows: Maximum number of suggestions to display at one time
31 * Type: Number, Range: 1 - 100, Default: 10
32 * delay: Number of ms to wait for the user to stop typing
33 * Type: Number, Range: 0 - 1200, Default: 120
34 * cache: Whether to cache results from a fetch
35 * Type: Boolean, Default: false
36 * cacheMaxAge: Number of ms to cache results from a fetch
37 * Type: Number, Range: 1 - Infinity, Default: 60000 (1 minute)
38 * submitOnClick: Whether to submit the form containing the textbox when a suggestion is clicked
39 * Type: Boolean, Default: false
40 * maxExpandFactor: Maximum suggestions box width relative to the textbox width. If set
41 * to e.g. 2, the suggestions box will never be grown beyond 2 times the width of the textbox.
42 * Type: Number, Range: 1 - infinity, Default: 3
43 * expandFrom: Which direction to offset the suggestion box from.
44 * Values 'start' and 'end' translate to left and right respectively depending on the
45 * directionality of the current document, according to $( 'html' ).css( 'direction' ).
46 * Type: String, default: 'auto', options: 'left', 'right', 'start', 'end', 'auto'.
47 * positionFromLeft: Sets expandFrom=left, for backwards compatibility
48 * Type: Boolean, Default: true
49 * highlightInput: Whether to hightlight matched portions of the input or not
50 * Type: Boolean, Default: false
54 var hasOwn = Object.hasOwnProperty;
58 * Cancel any delayed maybeFetch() call and callback the context so
59 * they can cancel any async fetching if they use AJAX or something.
61 cancel: function ( context ) {
62 if ( context.data.timerID !== null ) {
63 clearTimeout( context.data.timerID );
65 if ( $.isFunction( context.config.cancel ) ) {
66 context.config.cancel.call( context.data.$textbox );
71 * Hide the element with suggestions and clean up some state.
73 hide: function ( context ) {
74 // Remove any highlights, including on "special" items
75 context.data.$container.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
77 context.data.$container.hide();
81 * Restore the text the user originally typed in the textbox, before it
82 * was overwritten by highlight(). This restores the value the currently
83 * displayed suggestions are based on, rather than the value just before
84 * highlight() overwrote it; the former is arguably slightly more sensible.
86 restore: function ( context ) {
87 context.data.$textbox.val( context.data.prevText );
91 * Ask the user-specified callback for new suggestions. Any previous delayed
92 * call to this function still pending will be canceled. If the value in the
93 * textbox is empty or hasn't changed since the last time suggestions were fetched,
94 * this function does nothing.
95 * @param {Boolean} delayed Whether or not to delay this by the currently configured amount of time
97 update: function ( context, delayed ) {
98 function maybeFetch() {
99 var val = context.data.$textbox.val(),
100 cache = context.data.cache,
103 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
104 // if the textbox is empty then clear the result div, but leave other settings intouched
105 if ( val.length === 0 ) {
106 $.suggestions.hide( context );
107 context.data.prevText = '';
109 val !== context.data.prevText ||
110 !context.data.$container.is( ':visible' )
112 context.data.prevText = val;
114 if ( context.config.cache && hasOwn.call( cache, val ) ) {
115 if ( +new Date() - cache[ val ].timestamp < context.config.cacheMaxAge ) {
116 context.data.$textbox.suggestions( 'suggestions', cache[ val ].suggestions );
123 if ( !cacheHit && typeof context.config.fetch === 'function' ) {
124 context.config.fetch.call(
125 context.data.$textbox,
127 function ( suggestions ) {
128 suggestions = suggestions.slice( 0, context.config.maxRows );
129 context.data.$textbox.suggestions( 'suggestions', suggestions );
130 if ( context.config.cache ) {
132 suggestions: suggestions,
133 timestamp: +new Date()
137 context.config.maxRows
142 // Always update special rendering
143 $.suggestions.special( context );
146 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
147 $.suggestions.cancel( context );
150 // To avoid many started/aborted requests while typing, we're gonna take a short
151 // break before trying to fetch data.
152 context.data.timerID = setTimeout( maybeFetch, context.config.delay );
158 special: function ( context ) {
159 // Allow custom rendering - but otherwise don't do any rendering
160 if ( typeof context.config.special.render === 'function' ) {
161 // Wait for the browser to update the value
162 setTimeout( function () {
164 var $special = context.data.$container.find( '.suggestions-special' );
165 context.config.special.render.call( $special, context.data.$textbox.val(), context );
171 * Sets the value of a property, and updates the widget accordingly
172 * @param property String Name of property
173 * @param value Mixed Value to set property with
175 configure: function ( context, property, value ) {
177 $result, $results, $spanForWidth, childrenWidth,
178 i, expWidth, maxWidth, text;
180 // Validate creation using fallback values
181 switch ( property ) {
188 context.config[property] = value;
191 context.config[property] = value;
192 // Update suggestions
193 if ( context.data !== undefined ) {
194 if ( context.data.$textbox.val().length === 0 ) {
195 // Hide the div when no suggestion exist
196 $.suggestions.hide( context );
198 // Rebuild the suggestions list
199 context.data.$container.show();
200 // Update the size and position of the list
202 top: context.config.$region.offset().top + context.config.$region.outerHeight(),
204 width: context.config.$region.outerWidth(),
208 // Process expandFrom, after this it is set to left or right.
209 context.config.expandFrom = ( function ( expandFrom ) {
210 var regionWidth, docWidth, regionCenter, docCenter,
211 docDir = $( document.documentElement ).css( 'direction' ),
212 $region = context.config.$region;
214 // Backwards compatible
215 if ( context.config.positionFromLeft ) {
218 // Catch invalid values, default to 'auto'
219 } else if ( $.inArray( expandFrom, ['left', 'right', 'start', 'end', 'auto'] ) === -1 ) {
223 if ( expandFrom === 'auto' ) {
224 if ( $region.data( 'searchsuggest-expand-dir' ) ) {
225 // If the markup explicitly contains a direction, use it.
226 expandFrom = $region.data( 'searchsuggest-expand-dir' );
228 regionWidth = $region.outerWidth();
229 docWidth = $( document ).width();
230 if ( regionWidth > ( 0.85 * docWidth ) ) {
231 // If the input size takes up more than 85% of the document horizontally
232 // expand the suggestions to the writing direction's native end.
233 expandFrom = 'start';
235 // Calculate the center points of the input and document
236 regionCenter = $region.offset().left + regionWidth / 2;
237 docCenter = docWidth / 2;
238 if ( Math.abs( regionCenter - docCenter ) < ( 0.10 * docCenter ) ) {
239 // If the input's center is within 10% of the document center
240 // use the writing direction's native end.
241 expandFrom = 'start';
243 // Otherwise expand the input from the closest side of the page,
244 // towards the side of the page with the most free open space
245 expandFrom = regionCenter > docCenter ? 'right' : 'left';
251 if ( expandFrom === 'start' ) {
252 expandFrom = docDir === 'rtl' ? 'right' : 'left';
254 } else if ( expandFrom === 'end' ) {
255 expandFrom = docDir === 'rtl' ? 'left' : 'right';
260 }( context.config.expandFrom ) );
262 if ( context.config.expandFrom === 'left' ) {
264 newCSS.left = context.config.$region.offset().left;
265 newCSS.right = 'auto';
268 newCSS.left = 'auto';
269 newCSS.right = $( 'body' ).width() - ( context.config.$region.offset().left + context.config.$region.outerWidth() );
272 context.data.$container.css( newCSS );
273 $results = context.data.$container.children( '.suggestions-results' );
276 for ( i = 0; i < context.config.suggestions.length; i++ ) {
277 /*jshint loopfunc:true */
278 text = context.config.suggestions[i];
279 $result = $( '<div>' )
280 .addClass( 'suggestions-result' )
282 .data( 'text', context.config.suggestions[i] )
283 .mousemove( function () {
284 context.data.selectedWithMouse = true;
285 $.suggestions.highlight(
287 $( this ).closest( '.suggestions-results .suggestions-result' ),
291 .appendTo( $results );
292 // Allow custom rendering
293 if ( typeof context.config.result.render === 'function' ) {
294 context.config.result.render.call( $result, context.config.suggestions[i], context );
296 $result.text( text );
299 if ( context.config.highlightInput ) {
300 $result.highlightText( context.data.prevText );
303 // Widen results box if needed (new width is only calculated here, applied later).
305 // The monstrosity below accomplishes two things:
306 // * Wraps the text contents in a DOM element, so that we can know its width. There is
307 // no way to directly access the width of a text node, and we can't use the parent
308 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
309 // it, which trims it to a smaller width.
310 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
311 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
312 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
313 // still report the "trimmed" width. This should not be done in regular CSS
314 // stylesheets as we don't want this rule to apply to other <span> elements, like
315 // the ones generated by jquery.highlightText.
316 $spanForWidth = $result.wrapInner( '<span>' ).children();
317 childrenWidth = $spanForWidth.css( 'position', 'absolute' ).outerWidth();
318 $spanForWidth.contents().unwrap();
320 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
321 // factor in any padding, margin, or border space on the parent
322 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
326 // Apply new width for results box, if any
327 if ( expWidth > context.data.$container.width() ) {
328 maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
329 context.data.$container.width( Math.min( expWidth, maxWidth ) );
335 context.config[property] = Math.max( 1, Math.min( 100, value ) );
338 context.config[property] = Math.max( 0, Math.min( 1200, value ) );
341 context.config[property] = Math.max( 1, value );
343 case 'maxExpandFactor':
344 context.config[property] = Math.max( 1, value );
347 case 'submitOnClick':
348 case 'positionFromLeft':
349 case 'highlightInput':
350 context.config[property] = !!value;
356 * Highlight a result in the results table
357 * @param result <tr> to highlight: jQuery object, or 'prev' or 'next'
358 * @param updateTextbox If true, put the suggestion in the textbox
360 highlight: function ( context, result, updateTextbox ) {
361 var selected = context.data.$container.find( '.suggestions-result-current' );
362 if ( !result.get || selected.get( 0 ) !== result.get( 0 ) ) {
363 if ( result === 'prev' ) {
364 if ( selected.hasClass( 'suggestions-special' ) ) {
365 result = context.data.$container.find( '.suggestions-result:last' );
367 result = selected.prev();
368 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
369 // there is something in the DOM between selected element and the wrapper, bypass it
370 result = selected.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
373 if ( selected.length === 0 ) {
374 // we are at the beginning, so lets jump to the last item
375 if ( context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
376 result = context.data.$container.find( '.suggestions-special' );
378 result = context.data.$container.find( '.suggestions-results .suggestions-result:last' );
382 } else if ( result === 'next' ) {
383 if ( selected.length === 0 ) {
384 // No item selected, go to the first one
385 result = context.data.$container.find( '.suggestions-results .suggestions-result:first' );
386 if ( result.length === 0 && context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
387 // No suggestion exists, go to the special one directly
388 result = context.data.$container.find( '.suggestions-special' );
391 result = selected.next();
392 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
393 // there is something in the DOM between selected element and the wrapper, bypass it
394 result = selected.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
397 if ( selected.hasClass( 'suggestions-special' ) ) {
400 result.length === 0 &&
401 context.data.$container.find( '.suggestions-special' ).html() !== ''
403 // We were at the last item, jump to the specials!
404 result = context.data.$container.find( '.suggestions-special' );
408 selected.removeClass( 'suggestions-result-current' );
409 result.addClass( 'suggestions-result-current' );
411 if ( updateTextbox ) {
412 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
413 $.suggestions.restore( context );
415 context.data.$textbox.val( result.data( 'text' ) );
416 // .val() doesn't call any event handlers, so
417 // let the world know what happened
418 context.data.$textbox.change();
420 context.data.$textbox.trigger( 'change' );
425 * Respond to keypress event
426 * @param key Integer Code of key pressed
428 keypress: function ( e, context, key ) {
430 wasVisible = context.data.$container.is( ':visible' ),
431 preventDefault = false;
437 $.suggestions.highlight( context, 'next', true );
438 context.data.selectedWithMouse = false;
440 $.suggestions.update( context, false );
442 preventDefault = true;
447 $.suggestions.highlight( context, 'prev', true );
448 context.data.selectedWithMouse = false;
450 preventDefault = wasVisible;
454 $.suggestions.hide( context );
455 $.suggestions.restore( context );
456 $.suggestions.cancel( context );
457 context.data.$textbox.trigger( 'change' );
458 preventDefault = wasVisible;
462 preventDefault = wasVisible;
463 selected = context.data.$container.find( '.suggestions-result-current' );
464 $.suggestions.hide( context );
465 if ( selected.length === 0 || context.data.selectedWithMouse ) {
466 // If nothing is selected or if something was selected with the mouse
467 // cancel any current requests and allow the form to be submitted
468 // (simply don't prevent default behavior).
469 $.suggestions.cancel( context );
470 preventDefault = false;
471 } else if ( selected.is( '.suggestions-special' ) ) {
472 if ( typeof context.config.special.select === 'function' ) {
473 // Allow the callback to decide whether to prevent default or not
474 if ( context.config.special.select.call( selected, context.data.$textbox ) === true ) {
475 preventDefault = false;
479 if ( typeof context.config.result.select === 'function' ) {
480 // Allow the callback to decide whether to prevent default or not
481 if ( context.config.result.select.call( selected, context.data.$textbox ) === true ) {
482 preventDefault = false;
488 $.suggestions.update( context, true );
491 if ( preventDefault ) {
497 $.fn.suggestions = function () {
499 // Multi-context fields
503 $( this ).each( function () {
506 /* Construction / Loading */
508 context = $( this ).data( 'suggestions-context' );
509 if ( context === undefined || context === null ) {
512 fetch: function () {},
513 cancel: function () {},
522 submitOnClick: false,
525 highlightInput: false
532 // Handle various calling styles
533 if ( args.length > 0 ) {
534 if ( typeof args[0] === 'object' ) {
535 // Apply set of properties
536 for ( key in args[0] ) {
537 $.suggestions.configure( context, key, args[0][key] );
539 } else if ( typeof args[0] === 'string' ) {
540 if ( args.length > 1 ) {
541 // Set property values
542 $.suggestions.configure( context, args[0], args[1] );
543 } else if ( returnValue === null || returnValue === undefined ) {
544 // Get property values, but don't give access to internal data - returns only the first
545 returnValue = ( args[0] in context.config ? undefined : context.config[args[0]] );
552 if ( context.data === undefined ) {
554 // ID of running timer
557 // Text in textbox when suggestions were last fetched
560 // Cache of fetched suggestions
563 // Number of results visible without scrolling
566 // Suggestion the last mousedown event occurred on
567 mouseDownOn: $( [] ),
569 selectedWithMouse: false
572 context.data.$container = $( '<div>' )
573 .css( 'display', 'none' )
574 .addClass( 'suggestions' )
576 $( '<div>' ).addClass( 'suggestions-results' )
577 // Can't use click() because the container div is hidden when the
578 // textbox loses focus. Instead, listen for a mousedown followed
579 // by a mouseup on the same div.
580 .mousedown( function ( e ) {
581 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results .suggestions-result' );
583 .mouseup( function ( e ) {
584 var $result = $( e.target ).closest( '.suggestions-results .suggestions-result' ),
585 $other = context.data.mouseDownOn;
587 context.data.mouseDownOn = $( [] );
588 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
591 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
592 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
593 $.suggestions.highlight( context, $result, true );
594 if ( typeof context.config.result.select === 'function' ) {
595 context.config.result.select.call( $result, context.data.$textbox );
597 // This will hide the link we're just clicking on, which causes problems
598 // when done synchronously in at least Firefox 3.6 (bug 62858).
599 setTimeout( function () {
600 $.suggestions.hide( context );
603 // Always bring focus to the textbox, as that's probably where the user expects it
604 // if they were just typing.
605 context.data.$textbox.focus();
609 $( '<div>' ).addClass( 'suggestions-special' )
610 // Can't use click() because the container div is hidden when the
611 // textbox loses focus. Instead, listen for a mousedown followed
612 // by a mouseup on the same div.
613 .mousedown( function ( e ) {
614 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
616 .mouseup( function ( e ) {
617 var $special = $( e.target ).closest( '.suggestions-special' ),
618 $other = context.data.mouseDownOn;
620 context.data.mouseDownOn = $( [] );
621 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
624 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
625 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
626 if ( typeof context.config.special.select === 'function' ) {
627 context.config.special.select.call( $special, context.data.$textbox );
629 // This will hide the link we're just clicking on, which causes problems
630 // when done synchronously in at least Firefox 3.6 (bug 62858).
631 setTimeout( function () {
632 $.suggestions.hide( context );
635 // Always bring focus to the textbox, as that's probably where the user expects it
636 // if they were just typing.
637 context.data.$textbox.focus();
639 .mousemove( function ( e ) {
640 context.data.selectedWithMouse = true;
641 $.suggestions.highlight(
642 context, $( e.target ).closest( '.suggestions-special' ), false
646 .appendTo( $( 'body' ) );
649 // Stop browser autocomplete from interfering
650 .attr( 'autocomplete', 'off' )
651 .keydown( function ( e ) {
652 // Store key pressed to handle later
653 context.data.keypressed = e.which;
654 context.data.keypressedCount = 0;
656 .keypress( function ( e ) {
657 context.data.keypressedCount++;
658 $.suggestions.keypress( e, context, context.data.keypressed );
660 .keyup( function ( e ) {
661 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
662 // keypress in between, solve it
663 if ( context.data.keypressedCount === 0 ) {
664 $.suggestions.keypress( e, context, context.data.keypressed );
668 // When losing focus because of a mousedown
669 // on a suggestion, don't hide the suggestions
670 if ( context.data.mouseDownOn.length > 0 ) {
673 $.suggestions.hide( context );
674 $.suggestions.cancel( context );
678 // Store the context for next time
679 $( this ).data( 'suggestions-context', context );
681 return returnValue !== undefined ? returnValue : $( this );