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. Executed in the context of the
19 * cancel: Callback function to call when any pending asynchronous suggestions fetches should be canceled.
20 * 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 to e.g. 2, the suggestions box
37 * 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 directionality
41 * 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 updateSuggestions() call and inform the user so
53 * they can cancel their result 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
);
64 * Restore the text the user originally typed in the textbox, before it was overwritten by highlight(). This
65 * restores the value the currently displayed suggestions are based on, rather than the value just before
66 * highlight() overwrote it; the former is arguably slightly more sensible.
68 restore: function ( context
) {
69 context
.data
.$textbox
.val( context
.data
.prevText
);
72 * Ask the user-specified callback for new suggestions. Any previous delayed call to this function still pending
73 * will be canceled. If the value in the textbox is empty or hasn't changed since the last time suggestions were fetched, this
74 * function does nothing.
75 * @param {Boolean} delayed Whether or not to delay this by the currently configured amount of time
77 update: function ( context
, delayed
) {
78 // Only fetch if the value in the textbox changed and is not empty
79 // if the textbox is empty then clear the result div, but leave other settings intouched
80 function maybeFetch() {
81 if ( context
.data
.$textbox
.val().length
=== 0 ) {
82 context
.data
.$container
.hide();
83 context
.data
.prevText
= '';
84 } else if ( context
.data
.$textbox
.val() !== context
.data
.prevText
) {
85 if ( typeof context
.config
.fetch
=== 'function' ) {
86 context
.data
.prevText
= context
.data
.$textbox
.val();
87 context
.config
.fetch
.call( context
.data
.$textbox
, context
.data
.$textbox
.val() );
92 // Cancel previous call
93 if ( context
.data
.timerID
!== null ) {
94 clearTimeout( context
.data
.timerID
);
97 // Start a new asynchronous call
98 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
102 $.suggestions
.special( context
);
104 special: function ( context
) {
105 // Allow custom rendering - but otherwise don't do any rendering
106 if ( typeof context
.config
.special
.render
=== 'function' ) {
107 // Wait for the browser to update the value
108 setTimeout( function () {
110 var $special
= context
.data
.$container
.find( '.suggestions-special' );
111 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val() );
116 * Sets the value of a property, and updates the widget accordingly
117 * @param property String Name of property
118 * @param value Mixed Value to set property with
120 configure: function ( context
, property
, value
) {
122 // Validate creation using fallback values
130 context
.config
[property
] = value
;
133 context
.config
[property
] = value
;
134 // Update suggestions
135 if ( context
.data
!== undefined ) {
136 if ( context
.data
.$textbox
.val().length
=== 0 ) {
137 // Hide the div when no suggestion exist
138 context
.data
.$container
.hide();
140 // Rebuild the suggestions list
141 context
.data
.$container
.show();
142 // Update the size and position of the list
144 top
: context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
146 width
: context
.config
.$region
.outerWidth(),
150 // Process expandFrom, after this it is set to left or right.
151 context
.config
.expandFrom
= ( function ( expandFrom
) {
152 var regionWidth
, docWidth
, regionCenter
, docCenter
,
153 docDir
= $( document
.documentElement
).css( 'direction' ),
154 $region
= context
.config
.$region
;
156 // Backwards compatible
157 if ( context
.config
.positionFromLeft
) {
160 // Catch invalid values, default to 'auto'
161 } else if ( $.inArray( expandFrom
, ['left', 'right', 'start', 'end', 'auto'] ) === -1 ) {
165 if ( expandFrom
=== 'auto' ) {
166 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
167 // If the markup explicitly contains a direction, use it.
168 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
170 regionWidth
= $region
.outerWidth();
171 docWidth
= $( document
).width();
172 if ( ( regionWidth
/ docWidth
) > 0.85 ) {
173 // If the input size takes up more than 85% of the document horizontally
174 // expand the suggestions to the writing direction's native end.
175 expandFrom
= 'start';
177 // Calculate the center points of the input and document
178 regionCenter
= $region
.offset().left
+ regionWidth
/ 2;
179 docCenter
= docWidth
/ 2;
180 if ( Math
.abs( regionCenter
- docCenter
) / docCenter
< 0.10 ) {
181 // If the input's center is within 10% of the document center
182 // use the writing direction's native end.
183 expandFrom
= 'start';
185 // Otherwise expand the input from the closest side of the page,
186 // towards the side of the page with the most free open space
187 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
193 if ( expandFrom
=== 'start' ) {
194 expandFrom
= docDir
=== 'rtl' ? 'right': 'left';
196 } else if ( expandFrom
=== 'end' ) {
197 expandFrom
= docDir
=== 'rtl' ? 'left': 'right';
202 }( context
.config
.expandFrom
) );
204 if ( context
.config
.expandFrom
=== 'left' ) {
206 newCSS
.left
= context
.config
.$region
.offset().left
;
207 newCSS
.right
= 'auto';
210 newCSS
.left
= 'auto';
211 newCSS
.right
= $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
214 context
.data
.$container
.css( newCSS
);
215 var $results
= context
.data
.$container
.children( '.suggestions-results' );
218 var $autoEllipseMe
= $( [] );
219 var matchedText
= null;
220 for ( var i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
221 /*jshint loopfunc:true */
222 var text
= context
.config
.suggestions
[i
];
223 var $result
= $( '<div>' )
224 .addClass( 'suggestions-result' )
226 .data( 'text', context
.config
.suggestions
[i
] )
227 .mousemove( function ( e
) {
228 context
.data
.selectedWithMouse
= true;
229 $.suggestions
.highlight(
230 context
, $(this).closest( '.suggestions-results div' ), false
233 .appendTo( $results
);
234 // Allow custom rendering
235 if ( typeof context
.config
.result
.render
=== 'function' ) {
236 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[i
] );
238 // Add <span> with text
239 if( context
.config
.highlightInput
) {
240 matchedText
= context
.data
.prevText
;
242 $result
.append( $( '<span>' )
243 .css( 'whiteSpace', 'nowrap' )
247 // Widen results box if needed
248 // New width is only calculated here, applied later
249 var $span
= $result
.children( 'span' );
250 if ( $span
.outerWidth() > $result
.width() && $span
.outerWidth() > expWidth
) {
251 // factor in any padding, margin, or border space on the parent
252 expWidth
= $span
.outerWidth() + ( context
.data
.$container
.width() - $span
.parent().width());
254 $autoEllipseMe
= $autoEllipseMe
.add( $result
);
257 // Apply new width for results box, if any
258 if ( expWidth
> context
.data
.$container
.width() ) {
259 var maxWidth
= context
.config
.maxExpandFactor
*context
.data
.$textbox
.width();
260 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
262 // autoEllipse the results. Has to be done after changing the width
263 $autoEllipseMe
.autoEllipsis( { hasSpan
: true, tooltip
: true, matchText
: matchedText
} );
268 context
.config
[property
] = Math
.max( 1, Math
.min( 100, value
) );
271 context
.config
[property
] = Math
.max( 0, Math
.min( 1200, value
) );
273 case 'maxExpandFactor':
274 context
.config
[property
] = Math
.max( 1, value
);
276 case 'submitOnClick':
277 case 'positionFromLeft':
278 case 'highlightInput':
279 context
.config
[property
] = value
? true : false;
284 * Highlight a result in the results table
285 * @param result <tr> to highlight: jQuery object, or 'prev' or 'next'
286 * @param updateTextbox If true, put the suggestion in the textbox
288 highlight: function ( context
, result
, updateTextbox
) {
289 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
290 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
291 if ( result
=== 'prev' ) {
292 if( selected
.is( '.suggestions-special' ) ) {
293 result
= context
.data
.$container
.find( '.suggestions-result:last' );
295 result
= selected
.prev();
296 if ( selected
.length
=== 0 ) {
297 // we are at the beginning, so lets jump to the last item
298 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
299 result
= context
.data
.$container
.find( '.suggestions-special' );
301 result
= context
.data
.$container
.find( '.suggestions-results div:last' );
305 } else if ( result
=== 'next' ) {
306 if ( selected
.length
=== 0 ) {
307 // No item selected, go to the first one
308 result
= context
.data
.$container
.find( '.suggestions-results div:first' );
309 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
310 // No suggestion exists, go to the special one directly
311 result
= context
.data
.$container
.find( '.suggestions-special' );
314 result
= selected
.next();
315 if ( selected
.is( '.suggestions-special' ) ) {
318 result
.length
=== 0 &&
319 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
321 // We were at the last item, jump to the specials!
322 result
= context
.data
.$container
.find( '.suggestions-special' );
326 selected
.removeClass( 'suggestions-result-current' );
327 result
.addClass( 'suggestions-result-current' );
329 if ( updateTextbox
) {
330 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
331 $.suggestions
.restore( context
);
333 context
.data
.$textbox
.val( result
.data( 'text' ) );
334 // .val() doesn't call any event handlers, so
335 // let the world know what happened
336 context
.data
.$textbox
.change();
338 context
.data
.$textbox
.trigger( 'change' );
342 * Respond to keypress event
343 * @param key Integer Code of key pressed
345 keypress: function ( e
, context
, key
) {
346 var wasVisible
= context
.data
.$container
.is( ':visible' ),
347 preventDefault
= false;
352 $.suggestions
.highlight( context
, 'next', true );
353 context
.data
.selectedWithMouse
= false;
355 $.suggestions
.update( context
, false );
357 preventDefault
= true;
362 $.suggestions
.highlight( context
, 'prev', true );
363 context
.data
.selectedWithMouse
= false;
365 preventDefault
= wasVisible
;
369 context
.data
.$container
.hide();
370 $.suggestions
.restore( context
);
371 $.suggestions
.cancel( context
);
372 context
.data
.$textbox
.trigger( 'change' );
373 preventDefault
= wasVisible
;
377 context
.data
.$container
.hide();
378 preventDefault
= wasVisible
;
379 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
380 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
381 // if nothing is selected OR if something was selected with the mouse,
382 // cancel any current requests and submit the form
383 $.suggestions
.cancel( context
);
384 context
.config
.$region
.closest( 'form' ).submit();
385 } else if ( selected
.is( '.suggestions-special' ) ) {
386 if ( typeof context
.config
.special
.select
=== 'function' ) {
387 context
.config
.special
.select
.call( selected
, context
.data
.$textbox
);
390 if ( typeof context
.config
.result
.select
=== 'function' ) {
391 $.suggestions
.highlight( context
, selected
, true );
392 context
.config
.result
.select
.call( selected
, context
.data
.$textbox
);
394 $.suggestions
.highlight( context
, selected
, true );
399 $.suggestions
.update( context
, true );
402 if ( preventDefault
) {
404 e
.stopImmediatePropagation();
408 $.fn
.suggestions = function () {
410 // Multi-context fields
414 $(this).each( function () {
417 /* Construction / Loading */
419 context
= $(this).data( 'suggestions-context' );
420 if ( context
=== undefined || context
=== null ) {
423 'fetch' : function () {},
424 'cancel': function () {},
431 'submitOnClick': false,
432 'maxExpandFactor': 3,
433 'expandFrom': 'auto',
434 'highlightInput': false
441 // Handle various calling styles
442 if ( args
.length
> 0 ) {
443 if ( typeof args
[0] === 'object' ) {
444 // Apply set of properties
445 for ( key
in args
[0] ) {
446 $.suggestions
.configure( context
, key
, args
[0][key
] );
448 } else if ( typeof args
[0] === 'string' ) {
449 if ( args
.length
> 1 ) {
450 // Set property values
451 $.suggestions
.configure( context
, args
[0], args
[1] );
452 } else if ( returnValue
=== null || returnValue
=== undefined ) {
453 // Get property values, but don't give access to internal data - returns only the first
454 returnValue
= ( args
[0] in context
.config
? undefined : context
.config
[args
[0]] );
461 if ( context
.data
=== undefined ) {
463 // ID of running timer
466 // Text in textbox when suggestions were last fetched
469 // Number of results visible without scrolling
472 // Suggestion the last mousedown event occured on
473 mouseDownOn
: $( [] ),
475 selectedWithMouse
: false
478 context
.data
.$container
= $( '<div>' )
479 .css( 'display', 'none' )
480 .addClass( 'suggestions' )
482 $( '<div>' ).addClass( 'suggestions-results' )
483 // Can't use click() because the container div is hidden when the textbox loses focus. Instead,
484 // listen for a mousedown followed by a mouseup on the same div
485 .mousedown( function ( e
) {
486 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results div' );
488 .mouseup( function ( e
) {
489 var $result
= $( e
.target
).closest( '.suggestions-results div' );
490 var $other
= context
.data
.mouseDownOn
;
491 context
.data
.mouseDownOn
= $( [] );
492 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
495 $.suggestions
.highlight( context
, $result
, true );
496 context
.data
.$container
.hide();
497 if ( typeof context
.config
.result
.select
=== 'function' ) {
498 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
);
500 context
.data
.$textbox
.focus();
504 $( '<div>' ).addClass( 'suggestions-special' )
505 // Can't use click() because the container div is hidden when the textbox loses focus. Instead,
506 // listen for a mousedown followed by a mouseup on the same div
507 .mousedown( function ( e
) {
508 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
510 .mouseup( function ( e
) {
511 var $special
= $( e
.target
).closest( '.suggestions-special' );
512 var $other
= context
.data
.mouseDownOn
;
513 context
.data
.mouseDownOn
= $( [] );
514 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
517 context
.data
.$container
.hide();
518 if ( typeof context
.config
.special
.select
=== 'function' ) {
519 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
);
521 context
.data
.$textbox
.focus();
523 .mousemove( function ( e
) {
524 context
.data
.selectedWithMouse
= true;
525 $.suggestions
.highlight(
526 context
, $( e
.target
).closest( '.suggestions-special' ), false
530 .appendTo( $( 'body' ) );
533 // Stop browser autocomplete from interfering
534 .attr( 'autocomplete', 'off')
535 .keydown( function ( e
) {
536 // Store key pressed to handle later
537 context
.data
.keypressed
= e
.which
;
538 context
.data
.keypressedCount
= 0;
540 switch ( context
.data
.keypressed
) {
541 // This preventDefault logic is duplicated from
542 // $.suggestions.keypress(), which sucks
545 e
.stopImmediatePropagation();
550 if ( context
.data
.$container
.is( ':visible' ) ) {
552 e
.stopImmediatePropagation();
556 .keypress( function ( e
) {
557 context
.data
.keypressedCount
++;
558 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
560 .keyup( function ( e
) {
561 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
562 // keypress in between, solve it
563 if ( context
.data
.keypressedCount
=== 0 ) {
564 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
568 // When losing focus because of a mousedown
569 // on a suggestion, don't hide the suggestions
570 if ( context
.data
.mouseDownOn
.length
> 0 ) {
573 context
.data
.$container
.hide();
574 $.suggestions
.cancel( context
);
578 // Store the context for next time
579 $(this).data( 'suggestions-context', context
);
581 return returnValue
!== undefined ? returnValue
: $(this);