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: 7
32 * delay: Number of ms to wait for the user to stop typing
33 * Type: Number, Range: 0 - 1200, Default: 120
34 * submitOnClick: Whether to submit the form containing the textbox when a suggestion is clicked
35 * Type: Boolean, Default: false
36 * maxExpandFactor: Maximum suggestions box width relative to the textbox width. If set
37 * to e.g. 2, the suggestions box will never be grown beyond 2 times the width of the textbox.
38 * Type: Number, Range: 1 - infinity, Default: 3
39 * expandFrom: Which direction to offset the suggestion box from.
40 * Values 'start' and 'end' translate to left and right respectively depending on the
41 * directionality of the current document, according to $( 'html' ).css( 'direction' ).
42 * Type: String, default: 'auto', options: 'left', 'right', 'start', 'end', 'auto'.
43 * positionFromLeft: Sets expandFrom=left, for backwards compatibility
44 * Type: Boolean, Default: true
45 * highlightInput: Whether to hightlight matched portions of the input or not
46 * Type: Boolean, Default: false
52 * Cancel any delayed maybeFetch() call and callback the context so
53 * they can cancel any async fetching if they use AJAX or something.
55 cancel: function ( context
) {
56 if ( context
.data
.timerID
!== null ) {
57 clearTimeout( context
.data
.timerID
);
59 if ( $.isFunction( context
.config
.cancel
) ) {
60 context
.config
.cancel
.call( context
.data
.$textbox
);
65 * Hide the element with suggestions and clean up some state.
67 hide: function ( context
) {
68 // Remove any highlights, including on "special" items
69 context
.data
.$container
.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
71 context
.data
.$container
.hide();
75 * Restore the text the user originally typed in the textbox, before it
76 * was overwritten by highlight(). This restores the value the currently
77 * displayed suggestions are based on, rather than the value just before
78 * highlight() overwrote it; the former is arguably slightly more sensible.
80 restore: function ( context
) {
81 context
.data
.$textbox
.val( context
.data
.prevText
);
85 * Ask the user-specified callback for new suggestions. Any previous delayed
86 * call to this function still pending will be canceled. If the value in the
87 * textbox is empty or hasn't changed since the last time suggestions were fetched,
88 * this function does nothing.
89 * @param {Boolean} delayed Whether or not to delay this by the currently configured amount of time
91 update: function ( context
, delayed
) {
92 function maybeFetch() {
93 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
94 // if the textbox is empty then clear the result div, but leave other settings intouched
95 if ( context
.data
.$textbox
.val().length
=== 0 ) {
96 $.suggestions
.hide( context
);
97 context
.data
.prevText
= '';
99 context
.data
.$textbox
.val() !== context
.data
.prevText
||
100 !context
.data
.$container
.is( ':visible' )
102 if ( typeof context
.config
.fetch
=== 'function' ) {
103 context
.data
.prevText
= context
.data
.$textbox
.val();
104 context
.config
.fetch
.call( context
.data
.$textbox
, context
.data
.$textbox
.val() );
108 // Always update special rendering
109 $.suggestions
.special( context
);
112 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
113 $.suggestions
.cancel( context
);
116 // To avoid many started/aborted requests while typing, we're gonna take a short
117 // break before trying to fetch data.
118 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
124 special: function ( context
) {
125 // Allow custom rendering - but otherwise don't do any rendering
126 if ( typeof context
.config
.special
.render
=== 'function' ) {
127 // Wait for the browser to update the value
128 setTimeout( function () {
130 var $special
= context
.data
.$container
.find( '.suggestions-special' );
131 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val(), context
);
137 * Sets the value of a property, and updates the widget accordingly
138 * @param property String Name of property
139 * @param value Mixed Value to set property with
141 configure: function ( context
, property
, value
) {
143 $result
, $results
, $spanForWidth
, childrenWidth
,
144 i
, expWidth
, maxWidth
, text
;
146 // Validate creation using fallback values
147 switch ( property
) {
154 context
.config
[property
] = value
;
157 context
.config
[property
] = value
;
158 // Update suggestions
159 if ( context
.data
!== undefined ) {
160 if ( context
.data
.$textbox
.val().length
=== 0 ) {
161 // Hide the div when no suggestion exist
162 $.suggestions
.hide( context
);
164 // Rebuild the suggestions list
165 context
.data
.$container
.show();
166 // Update the size and position of the list
168 top
: context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
170 width
: context
.config
.$region
.outerWidth(),
174 // Process expandFrom, after this it is set to left or right.
175 context
.config
.expandFrom
= ( function ( expandFrom
) {
176 var regionWidth
, docWidth
, regionCenter
, docCenter
,
177 docDir
= $( document
.documentElement
).css( 'direction' ),
178 $region
= context
.config
.$region
;
180 // Backwards compatible
181 if ( context
.config
.positionFromLeft
) {
184 // Catch invalid values, default to 'auto'
185 } else if ( $.inArray( expandFrom
, ['left', 'right', 'start', 'end', 'auto'] ) === -1 ) {
189 if ( expandFrom
=== 'auto' ) {
190 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
191 // If the markup explicitly contains a direction, use it.
192 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
194 regionWidth
= $region
.outerWidth();
195 docWidth
= $( document
).width();
196 if ( ( regionWidth
/ docWidth
) > 0.85 ) {
197 // If the input size takes up more than 85% of the document horizontally
198 // expand the suggestions to the writing direction's native end.
199 expandFrom
= 'start';
201 // Calculate the center points of the input and document
202 regionCenter
= $region
.offset().left
+ regionWidth
/ 2;
203 docCenter
= docWidth
/ 2;
204 if ( Math
.abs( regionCenter
- docCenter
) / docCenter
< 0.10 ) {
205 // If the input's center is within 10% of the document center
206 // use the writing direction's native end.
207 expandFrom
= 'start';
209 // Otherwise expand the input from the closest side of the page,
210 // towards the side of the page with the most free open space
211 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
217 if ( expandFrom
=== 'start' ) {
218 expandFrom
= docDir
=== 'rtl' ? 'right' : 'left';
220 } else if ( expandFrom
=== 'end' ) {
221 expandFrom
= docDir
=== 'rtl' ? 'left' : 'right';
226 }( context
.config
.expandFrom
) );
228 if ( context
.config
.expandFrom
=== 'left' ) {
230 newCSS
.left
= context
.config
.$region
.offset().left
;
231 newCSS
.right
= 'auto';
234 newCSS
.left
= 'auto';
235 newCSS
.right
= $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
238 context
.data
.$container
.css( newCSS
);
239 $results
= context
.data
.$container
.children( '.suggestions-results' );
242 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
243 /*jshint loopfunc:true */
244 text
= context
.config
.suggestions
[i
];
245 $result
= $( '<div>' )
246 .addClass( 'suggestions-result' )
248 .data( 'text', context
.config
.suggestions
[i
] )
249 .mousemove( function () {
250 context
.data
.selectedWithMouse
= true;
251 $.suggestions
.highlight(
253 $( this ).closest( '.suggestions-results .suggestions-result' ),
257 .appendTo( $results
);
258 // Allow custom rendering
259 if ( typeof context
.config
.result
.render
=== 'function' ) {
260 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[i
], context
);
262 $result
.text( text
);
265 if ( context
.config
.highlightInput
) {
266 $result
.highlightText( context
.data
.prevText
);
269 // Widen results box if needed (new width is only calculated here, applied later).
271 // The monstrosity below accomplishes two things:
272 // * Wraps the text contents in a DOM element, so that we can know its width. There is
273 // no way to directly access the width of a text node, and we can't use the parent
274 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
275 // it, which trims it to a smaller width.
276 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
277 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
278 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
279 // still report the "trimmed" width. This should not be done in regular CSS
280 // stylesheets as we don't want this rule to apply to other <span> elements, like
281 // the ones generated by jquery.highlightText.
282 $spanForWidth
= $result
.wrapInner( '<span>' ).children();
283 childrenWidth
= $spanForWidth
.css( 'position', 'absolute' ).outerWidth();
284 $spanForWidth
.contents().unwrap();
286 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
287 // factor in any padding, margin, or border space on the parent
288 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
292 // Apply new width for results box, if any
293 if ( expWidth
> context
.data
.$container
.width() ) {
294 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
295 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
301 context
.config
[property
] = Math
.max( 1, Math
.min( 100, value
) );
304 context
.config
[property
] = Math
.max( 0, Math
.min( 1200, value
) );
306 case 'maxExpandFactor':
307 context
.config
[property
] = Math
.max( 1, value
);
309 case 'submitOnClick':
310 case 'positionFromLeft':
311 case 'highlightInput':
312 context
.config
[property
] = value
? true : false;
318 * Highlight a result in the results table
319 * @param result <tr> to highlight: jQuery object, or 'prev' or 'next'
320 * @param updateTextbox If true, put the suggestion in the textbox
322 highlight: function ( context
, result
, updateTextbox
) {
323 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
324 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
325 if ( result
=== 'prev' ) {
326 if ( selected
.hasClass( 'suggestions-special' ) ) {
327 result
= context
.data
.$container
.find( '.suggestions-result:last' );
329 result
= selected
.prev();
330 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
331 // there is something in the DOM between selected element and the wrapper, bypass it
332 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
335 if ( selected
.length
=== 0 ) {
336 // we are at the beginning, so lets jump to the last item
337 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
338 result
= context
.data
.$container
.find( '.suggestions-special' );
340 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:last' );
344 } else if ( result
=== 'next' ) {
345 if ( selected
.length
=== 0 ) {
346 // No item selected, go to the first one
347 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:first' );
348 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
349 // No suggestion exists, go to the special one directly
350 result
= context
.data
.$container
.find( '.suggestions-special' );
353 result
= selected
.next();
354 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
355 // there is something in the DOM between selected element and the wrapper, bypass it
356 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
359 if ( selected
.hasClass( 'suggestions-special' ) ) {
362 result
.length
=== 0 &&
363 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
365 // We were at the last item, jump to the specials!
366 result
= context
.data
.$container
.find( '.suggestions-special' );
370 selected
.removeClass( 'suggestions-result-current' );
371 result
.addClass( 'suggestions-result-current' );
373 if ( updateTextbox
) {
374 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
375 $.suggestions
.restore( context
);
377 context
.data
.$textbox
.val( result
.data( 'text' ) );
378 // .val() doesn't call any event handlers, so
379 // let the world know what happened
380 context
.data
.$textbox
.change();
382 context
.data
.$textbox
.trigger( 'change' );
387 * Respond to keypress event
388 * @param key Integer Code of key pressed
390 keypress: function ( e
, context
, key
) {
392 wasVisible
= context
.data
.$container
.is( ':visible' ),
393 preventDefault
= false;
399 $.suggestions
.highlight( context
, 'next', true );
400 context
.data
.selectedWithMouse
= false;
402 $.suggestions
.update( context
, false );
404 preventDefault
= true;
409 $.suggestions
.highlight( context
, 'prev', true );
410 context
.data
.selectedWithMouse
= false;
412 preventDefault
= wasVisible
;
416 $.suggestions
.hide( context
);
417 $.suggestions
.restore( context
);
418 $.suggestions
.cancel( context
);
419 context
.data
.$textbox
.trigger( 'change' );
420 preventDefault
= wasVisible
;
424 preventDefault
= wasVisible
;
425 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
426 $.suggestions
.hide( context
);
427 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
428 // If nothing is selected or if something was selected with the mouse
429 // cancel any current requests and allow the form to be submitted
430 // (simply don't prevent default behavior).
431 $.suggestions
.cancel( context
);
432 preventDefault
= false;
433 } else if ( selected
.is( '.suggestions-special' ) ) {
434 if ( typeof context
.config
.special
.select
=== 'function' ) {
435 // Allow the callback to decide whether to prevent default or not
436 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
) === true ) {
437 preventDefault
= false;
441 $.suggestions
.highlight( context
, selected
, true );
443 if ( typeof context
.config
.result
.select
=== 'function' ) {
444 // Allow the callback to decide whether to prevent default or not
445 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
) === true ) {
446 preventDefault
= false;
452 $.suggestions
.update( context
, true );
455 if ( preventDefault
) {
461 $.fn
.suggestions = function () {
463 // Multi-context fields
467 $( this ).each( function () {
470 /* Construction / Loading */
472 context
= $( this ).data( 'suggestions-context' );
473 if ( context
=== undefined || context
=== null ) {
476 fetch: function () {},
477 cancel: function () {},
484 submitOnClick
: false,
487 highlightInput
: false
494 // Handle various calling styles
495 if ( args
.length
> 0 ) {
496 if ( typeof args
[0] === 'object' ) {
497 // Apply set of properties
498 for ( key
in args
[0] ) {
499 $.suggestions
.configure( context
, key
, args
[0][key
] );
501 } else if ( typeof args
[0] === 'string' ) {
502 if ( args
.length
> 1 ) {
503 // Set property values
504 $.suggestions
.configure( context
, args
[0], args
[1] );
505 } else if ( returnValue
=== null || returnValue
=== undefined ) {
506 // Get property values, but don't give access to internal data - returns only the first
507 returnValue
= ( args
[0] in context
.config
? undefined : context
.config
[args
[0]] );
514 if ( context
.data
=== undefined ) {
516 // ID of running timer
519 // Text in textbox when suggestions were last fetched
522 // Number of results visible without scrolling
525 // Suggestion the last mousedown event occurred on
526 mouseDownOn
: $( [] ),
528 selectedWithMouse
: false
531 context
.data
.$container
= $( '<div>' )
532 .css( 'display', 'none' )
533 .addClass( 'suggestions' )
535 $( '<div>' ).addClass( 'suggestions-results' )
536 // Can't use click() because the container div is hidden when the
537 // textbox loses focus. Instead, listen for a mousedown followed
538 // by a mouseup on the same div.
539 .mousedown( function ( e
) {
540 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
542 .mouseup( function ( e
) {
543 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
544 $other
= context
.data
.mouseDownOn
;
546 context
.data
.mouseDownOn
= $( [] );
547 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
550 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
551 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
552 $.suggestions
.highlight( context
, $result
, true );
553 if ( typeof context
.config
.result
.select
=== 'function' ) {
554 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
);
556 // This will hide the link we're just clicking on, which causes problems
557 // when done synchronously in at least Firefox 3.6 (bug 62858).
558 setTimeout( function () {
559 $.suggestions
.hide( context
);
562 // Always bring focus to the textbox, as that's probably where the user expects it
563 // if they were just typing.
564 context
.data
.$textbox
.focus();
568 $( '<div>' ).addClass( 'suggestions-special' )
569 // Can't use click() because the container div is hidden when the
570 // textbox loses focus. Instead, listen for a mousedown followed
571 // by a mouseup on the same div.
572 .mousedown( function ( e
) {
573 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
575 .mouseup( function ( e
) {
576 var $special
= $( e
.target
).closest( '.suggestions-special' ),
577 $other
= context
.data
.mouseDownOn
;
579 context
.data
.mouseDownOn
= $( [] );
580 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
583 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
584 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
585 if ( typeof context
.config
.special
.select
=== 'function' ) {
586 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
);
588 // This will hide the link we're just clicking on, which causes problems
589 // when done synchronously in at least Firefox 3.6 (bug 62858).
590 setTimeout( function () {
591 $.suggestions
.hide( context
);
594 // Always bring focus to the textbox, as that's probably where the user expects it
595 // if they were just typing.
596 context
.data
.$textbox
.focus();
598 .mousemove( function ( e
) {
599 context
.data
.selectedWithMouse
= true;
600 $.suggestions
.highlight(
601 context
, $( e
.target
).closest( '.suggestions-special' ), false
605 .appendTo( $( 'body' ) );
608 // Stop browser autocomplete from interfering
609 .attr( 'autocomplete', 'off' )
610 .keydown( function ( e
) {
611 // Store key pressed to handle later
612 context
.data
.keypressed
= e
.which
;
613 context
.data
.keypressedCount
= 0;
615 .keypress( function ( e
) {
616 context
.data
.keypressedCount
++;
617 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
619 .keyup( function ( e
) {
620 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
621 // keypress in between, solve it
622 if ( context
.data
.keypressedCount
=== 0 ) {
623 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
627 // When losing focus because of a mousedown
628 // on a suggestion, don't hide the suggestions
629 if ( context
.data
.mouseDownOn
.length
> 0 ) {
632 $.suggestions
.hide( context
);
633 $.suggestions
.cancel( context
);
637 // Store the context for next time
638 $( this ).data( 'suggestions-context', context
);
640 return returnValue
!== undefined ? returnValue
: $( this );