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 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
93 // if the textbox is empty then clear the result div, but leave other settings intouched
94 function maybeFetch() {
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() );
109 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
110 $.suggestions
.cancel( context
);
113 // To avoid many started/aborted requests while typing, we're gonna take a short
114 // break before trying to fetch data.
115 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
119 $.suggestions
.special( context
);
122 special: function ( context
) {
123 // Allow custom rendering - but otherwise don't do any rendering
124 if ( typeof context
.config
.special
.render
=== 'function' ) {
125 // Wait for the browser to update the value
126 setTimeout( function () {
128 var $special
= context
.data
.$container
.find( '.suggestions-special' );
129 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val(), context
);
135 * Sets the value of a property, and updates the widget accordingly
136 * @param property String Name of property
137 * @param value Mixed Value to set property with
139 configure: function ( context
, property
, value
) {
141 $result
, $results
, childrenWidth
,
142 i
, expWidth
, maxWidth
, text
;
144 // Validate creation using fallback values
145 switch ( property
) {
152 context
.config
[property
] = value
;
155 context
.config
[property
] = value
;
156 // Update suggestions
157 if ( context
.data
!== undefined ) {
158 if ( context
.data
.$textbox
.val().length
=== 0 ) {
159 // Hide the div when no suggestion exist
160 $.suggestions
.hide( context
);
162 // Rebuild the suggestions list
163 context
.data
.$container
.show();
164 // Update the size and position of the list
166 top
: context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
168 width
: context
.config
.$region
.outerWidth(),
172 // Process expandFrom, after this it is set to left or right.
173 context
.config
.expandFrom
= ( function ( expandFrom
) {
174 var regionWidth
, docWidth
, regionCenter
, docCenter
,
175 docDir
= $( document
.documentElement
).css( 'direction' ),
176 $region
= context
.config
.$region
;
178 // Backwards compatible
179 if ( context
.config
.positionFromLeft
) {
182 // Catch invalid values, default to 'auto'
183 } else if ( $.inArray( expandFrom
, ['left', 'right', 'start', 'end', 'auto'] ) === -1 ) {
187 if ( expandFrom
=== 'auto' ) {
188 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
189 // If the markup explicitly contains a direction, use it.
190 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
192 regionWidth
= $region
.outerWidth();
193 docWidth
= $( document
).width();
194 if ( ( regionWidth
/ docWidth
) > 0.85 ) {
195 // If the input size takes up more than 85% of the document horizontally
196 // expand the suggestions to the writing direction's native end.
197 expandFrom
= 'start';
199 // Calculate the center points of the input and document
200 regionCenter
= $region
.offset().left
+ regionWidth
/ 2;
201 docCenter
= docWidth
/ 2;
202 if ( Math
.abs( regionCenter
- docCenter
) / docCenter
< 0.10 ) {
203 // If the input's center is within 10% of the document center
204 // use the writing direction's native end.
205 expandFrom
= 'start';
207 // Otherwise expand the input from the closest side of the page,
208 // towards the side of the page with the most free open space
209 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
215 if ( expandFrom
=== 'start' ) {
216 expandFrom
= docDir
=== 'rtl' ? 'right': 'left';
218 } else if ( expandFrom
=== 'end' ) {
219 expandFrom
= docDir
=== 'rtl' ? 'left': 'right';
224 }( context
.config
.expandFrom
) );
226 if ( context
.config
.expandFrom
=== 'left' ) {
228 newCSS
.left
= context
.config
.$region
.offset().left
;
229 newCSS
.right
= 'auto';
232 newCSS
.left
= 'auto';
233 newCSS
.right
= $( document
).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
236 context
.data
.$container
.css( newCSS
);
237 $results
= context
.data
.$container
.children( '.suggestions-results' );
240 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
241 /*jshint loopfunc:true */
242 text
= context
.config
.suggestions
[i
];
243 $result
= $( '<div>' )
244 .addClass( 'suggestions-result' )
246 .data( 'text', context
.config
.suggestions
[i
] )
247 .mousemove( function () {
248 context
.data
.selectedWithMouse
= true;
249 $.suggestions
.highlight(
251 $(this).closest( '.suggestions-results .suggestions-result' ),
255 .appendTo( $results
);
256 // Allow custom rendering
257 if ( typeof context
.config
.result
.render
=== 'function' ) {
258 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[i
], context
);
260 $result
.text( text
);
263 if ( context
.config
.highlightInput
) {
264 $result
.highlightText( context
.data
.prevText
);
267 // Widen results box if needed
268 // New width is only calculated here, applied later
269 childrenWidth
= $result
.children().outerWidth();
270 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
271 // factor in any padding, margin, or border space on the parent
272 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
276 // Apply new width for results box, if any
277 if ( expWidth
> context
.data
.$container
.width() ) {
278 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
279 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
285 context
.config
[property
] = Math
.max( 1, Math
.min( 100, value
) );
288 context
.config
[property
] = Math
.max( 0, Math
.min( 1200, value
) );
290 case 'maxExpandFactor':
291 context
.config
[property
] = Math
.max( 1, value
);
293 case 'submitOnClick':
294 case 'positionFromLeft':
295 case 'highlightInput':
296 context
.config
[property
] = value
? true : false;
302 * Highlight a result in the results table
303 * @param result <tr> to highlight: jQuery object, or 'prev' or 'next'
304 * @param updateTextbox If true, put the suggestion in the textbox
306 highlight: function ( context
, result
, updateTextbox
) {
307 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
308 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
309 if ( result
=== 'prev' ) {
310 if( selected
.hasClass( 'suggestions-special' ) ) {
311 result
= context
.data
.$container
.find( '.suggestions-result:last' );
313 result
= selected
.prev();
314 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
315 // there is something in the DOM between selected element and the wrapper, bypass it
316 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq(0);
319 if ( selected
.length
=== 0 ) {
320 // we are at the beginning, so lets jump to the last item
321 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
322 result
= context
.data
.$container
.find( '.suggestions-special' );
324 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:last' );
328 } else if ( result
=== 'next' ) {
329 if ( selected
.length
=== 0 ) {
330 // No item selected, go to the first one
331 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:first' );
332 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
333 // No suggestion exists, go to the special one directly
334 result
= context
.data
.$container
.find( '.suggestions-special' );
337 result
= selected
.next();
338 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
339 // there is something in the DOM between selected element and the wrapper, bypass it
340 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq(0);
343 if ( selected
.hasClass( 'suggestions-special' ) ) {
346 result
.length
=== 0 &&
347 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
349 // We were at the last item, jump to the specials!
350 result
= context
.data
.$container
.find( '.suggestions-special' );
354 selected
.removeClass( 'suggestions-result-current' );
355 result
.addClass( 'suggestions-result-current' );
357 if ( updateTextbox
) {
358 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
359 $.suggestions
.restore( context
);
361 context
.data
.$textbox
.val( result
.data( 'text' ) );
362 // .val() doesn't call any event handlers, so
363 // let the world know what happened
364 context
.data
.$textbox
.change();
366 context
.data
.$textbox
.trigger( 'change' );
371 * Respond to keypress event
372 * @param key Integer Code of key pressed
374 keypress: function ( e
, context
, key
) {
376 wasVisible
= context
.data
.$container
.is( ':visible' ),
377 preventDefault
= false;
383 $.suggestions
.highlight( context
, 'next', true );
384 context
.data
.selectedWithMouse
= false;
386 $.suggestions
.update( context
, false );
388 preventDefault
= true;
393 $.suggestions
.highlight( context
, 'prev', true );
394 context
.data
.selectedWithMouse
= false;
396 preventDefault
= wasVisible
;
400 $.suggestions
.hide( context
);
401 $.suggestions
.restore( context
);
402 $.suggestions
.cancel( context
);
403 context
.data
.$textbox
.trigger( 'change' );
404 preventDefault
= wasVisible
;
408 preventDefault
= wasVisible
;
409 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
410 $.suggestions
.hide( context
);
411 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
412 // If nothing is selected or if something was selected with the mouse
413 // cancel any current requests and allow the form to be submitted
414 // (simply don't prevent default behavior).
415 $.suggestions
.cancel( context
);
416 preventDefault
= false;
417 } else if ( selected
.is( '.suggestions-special' ) ) {
418 if ( typeof context
.config
.special
.select
=== 'function' ) {
419 // Allow the callback to decide whether to prevent default or not
420 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
) === true ) {
421 preventDefault
= false;
425 $.suggestions
.highlight( context
, selected
, true );
427 if ( typeof context
.config
.result
.select
=== 'function' ) {
428 // Allow the callback to decide whether to prevent default or not
429 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
) === true ) {
430 preventDefault
= false;
436 $.suggestions
.update( context
, true );
439 if ( preventDefault
) {
445 $.fn
.suggestions = function () {
447 // Multi-context fields
451 $(this).each( function () {
454 /* Construction / Loading */
456 context
= $(this).data( 'suggestions-context' );
457 if ( context
=== undefined || context
=== null ) {
460 fetch: function () {},
461 cancel: function () {},
468 submitOnClick
: false,
471 highlightInput
: false
478 // Handle various calling styles
479 if ( args
.length
> 0 ) {
480 if ( typeof args
[0] === 'object' ) {
481 // Apply set of properties
482 for ( key
in args
[0] ) {
483 $.suggestions
.configure( context
, key
, args
[0][key
] );
485 } else if ( typeof args
[0] === 'string' ) {
486 if ( args
.length
> 1 ) {
487 // Set property values
488 $.suggestions
.configure( context
, args
[0], args
[1] );
489 } else if ( returnValue
=== null || returnValue
=== undefined ) {
490 // Get property values, but don't give access to internal data - returns only the first
491 returnValue
= ( args
[0] in context
.config
? undefined : context
.config
[args
[0]] );
498 if ( context
.data
=== undefined ) {
500 // ID of running timer
503 // Text in textbox when suggestions were last fetched
506 // Number of results visible without scrolling
509 // Suggestion the last mousedown event occured on
510 mouseDownOn
: $( [] ),
512 selectedWithMouse
: false
515 context
.data
.$container
= $( '<div>' )
516 .css( 'display', 'none' )
517 .addClass( 'suggestions' )
519 $( '<div>' ).addClass( 'suggestions-results' )
520 // Can't use click() because the container div is hidden when the
521 // textbox loses focus. Instead, listen for a mousedown followed
522 // by a mouseup on the same div.
523 .mousedown( function ( e
) {
524 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
526 .mouseup( function ( e
) {
527 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
528 $other
= context
.data
.mouseDownOn
;
530 context
.data
.mouseDownOn
= $( [] );
531 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
534 // do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click)
535 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
536 $.suggestions
.highlight( context
, $result
, true );
537 $.suggestions
.hide( context
);
538 if ( typeof context
.config
.result
.select
=== 'function' ) {
539 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
);
542 // but still restore focus to the textbox, so that the suggestions will be hidden properly
543 context
.data
.$textbox
.focus();
547 $( '<div>' ).addClass( 'suggestions-special' )
548 // Can't use click() because the container div is hidden when the
549 // textbox loses focus. Instead, listen for a mousedown followed
550 // by a mouseup on the same div.
551 .mousedown( function ( e
) {
552 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
554 .mouseup( function ( e
) {
555 var $special
= $( e
.target
).closest( '.suggestions-special' ),
556 $other
= context
.data
.mouseDownOn
;
558 context
.data
.mouseDownOn
= $( [] );
559 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
562 // do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click)
563 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
564 $.suggestions
.hide( context
);
565 if ( typeof context
.config
.special
.select
=== 'function' ) {
566 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
);
569 // but still restore focus to the textbox, so that the suggestions will be hidden properly
570 context
.data
.$textbox
.focus();
572 .mousemove( function ( e
) {
573 context
.data
.selectedWithMouse
= true;
574 $.suggestions
.highlight(
575 context
, $( e
.target
).closest( '.suggestions-special' ), false
579 .appendTo( $( 'body' ) );
582 // Stop browser autocomplete from interfering
583 .attr( 'autocomplete', 'off')
584 .keydown( function ( e
) {
585 // Store key pressed to handle later
586 context
.data
.keypressed
= e
.which
;
587 context
.data
.keypressedCount
= 0;
589 .keypress( function ( e
) {
590 context
.data
.keypressedCount
++;
591 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
593 .keyup( function ( e
) {
594 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
595 // keypress in between, solve it
596 if ( context
.data
.keypressedCount
=== 0 ) {
597 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
601 // When losing focus because of a mousedown
602 // on a suggestion, don't hide the suggestions
603 if ( context
.data
.mouseDownOn
.length
> 0 ) {
606 $.suggestions
.hide( context
);
607 $.suggestions
.cancel( context
);
611 // Store the context for next time
612 $(this).data( 'suggestions-context', context
);
614 return returnValue
!== undefined ? returnValue
: $(this);