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 * positionFromLeft: Whether to position the suggestion box with the left attribute or the right
40 * Type: Boolean, Default: true
41 * highlightInput: Whether to hightlight matched portions of the input or not
42 * Type: Boolean, Default: false
47 * Cancel any delayed updateSuggestions() call and inform the user so
48 * they can cancel their result fetching if they use AJAX or something
50 cancel: function( context
) {
51 if ( context
.data
.timerID
!= null ) {
52 clearTimeout( context
.data
.timerID
);
54 if ( typeof context
.config
.cancel
== 'function' ) {
55 context
.config
.cancel
.call( context
.data
.$textbox
);
59 * Restore the text the user originally typed in the textbox, before it was overwritten by highlight(). This
60 * restores the value the currently displayed suggestions are based on, rather than the value just before
61 * highlight() overwrote it; the former is arguably slightly more sensible.
63 restore: function( context
) {
64 context
.data
.$textbox
.val( context
.data
.prevText
);
67 * Ask the user-specified callback for new suggestions. Any previous delayed call to this function still pending
68 * will be canceled. If the value in the textbox hasn't changed since the last time suggestions were fetched, this
69 * function does nothing.
70 * @param {Boolean} delayed Whether or not to delay this by the currently configured amount of time
72 update: function( context
, delayed
) {
73 // Only fetch if the value in the textbox changed
74 function maybeFetch() {
75 if ( context
.data
.$textbox
.val() !== context
.data
.prevText
) {
76 context
.data
.prevText
= context
.data
.$textbox
.val();
77 if ( typeof context
.config
.fetch
== 'function' ) {
78 context
.config
.fetch
.call( context
.data
.$textbox
, context
.data
.$textbox
.val() );
82 // Cancel previous call
83 if ( context
.data
.timerID
!= null ) {
84 clearTimeout( context
.data
.timerID
);
87 // Start a new asynchronous call
88 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
92 $.suggestions
.special( context
);
94 special: function( context
) {
95 // Allow custom rendering - but otherwise don't do any rendering
96 if ( typeof context
.config
.special
.render
== 'function' ) {
97 // Wait for the browser to update the value
98 setTimeout( function() {
100 $special
= context
.data
.$container
.find( '.suggestions-special' );
101 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val() );
106 * Sets the value of a property, and updates the widget accordingly
107 * @param property String Name of property
108 * @param value Mixed Value to set property with
110 configure: function( context
, property
, value
) {
111 // Validate creation using fallback values
118 context
.config
[property
] = value
;
121 context
.config
[property
] = value
;
122 // Update suggestions
123 if ( typeof context
.data
!== 'undefined' ) {
124 if ( context
.data
.$textbox
.val().length
== 0 ) {
125 // Hide the div when no suggestion exist
126 context
.data
.$container
.hide();
128 // Rebuild the suggestions list
129 context
.data
.$container
.show();
130 // Update the size and position of the list
132 'top': context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
134 'width': context
.config
.$region
.outerWidth(),
137 if ( context
.config
.positionFromLeft
) {
138 newCSS
['left'] = context
.config
.$region
.offset().left
;
139 newCSS
['right'] = 'auto';
141 newCSS
['left'] = 'auto';
142 newCSS
['right'] = $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
144 context
.data
.$container
.css( newCSS
);
145 var $results
= context
.data
.$container
.children( '.suggestions-results' );
148 var $autoEllipseMe
= $( [] );
149 var matchedText
= null;
150 for ( var i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
151 var text
= context
.config
.suggestions
[i
];
152 var $result
= $( '<div />' )
153 .addClass( 'suggestions-result' )
155 .data( 'text', context
.config
.suggestions
[i
] )
156 .mousemove( function( e
) {
157 context
.data
.selectedWithMouse
= true;
158 $.suggestions
.highlight(
159 context
, $(this).closest( '.suggestions-results div' ), false
162 .appendTo( $results
);
163 // Allow custom rendering
164 if ( typeof context
.config
.result
.render
== 'function' ) {
165 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[i
] );
167 // Add <span> with text
168 if( context
.config
.highlightInput
) {
169 matchedText
= context
.data
.prevText
;
171 $result
.append( $( '<span />' )
172 .css( 'whiteSpace', 'nowrap' )
176 // Widen results box if needed
177 // New width is only calculated here, applied later
178 var $span
= $result
.children( 'span' );
179 if ( $span
.outerWidth() > $result
.width() && $span
.outerWidth() > expWidth
) {
180 // factor in any padding, margin, or border space on the parent
181 expWidth
= $span
.outerWidth() + ( context
.data
.$container
.width() - $span
.parent().width());
183 $autoEllipseMe
= $autoEllipseMe
.add( $result
);
186 // Apply new width for results box, if any
187 if ( expWidth
> context
.data
.$container
.width() ) {
188 var maxWidth
= context
.config
.maxExpandFactor
*context
.data
.$textbox
.width();
189 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
191 // autoEllipse the results. Has to be done after changing the width
192 $autoEllipseMe
.autoEllipsis( { hasSpan
: true, tooltip
: true, matchText
: matchedText
} );
197 context
.config
[property
] = Math
.max( 1, Math
.min( 100, value
) );
200 context
.config
[property
] = Math
.max( 0, Math
.min( 1200, value
) );
202 case 'maxExpandFactor':
203 context
.config
[property
] = Math
.max( 1, value
);
205 case 'submitOnClick':
206 case 'positionFromLeft':
207 case 'highlightInput':
208 context
.config
[property
] = value
? true : false;
213 * Highlight a result in the results table
214 * @param result <tr> to highlight: jQuery object, or 'prev' or 'next'
215 * @param updateTextbox If true, put the suggestion in the textbox
217 highlight: function( context
, result
, updateTextbox
) {
218 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
219 if ( !result
.get || selected
.get( 0 ) != result
.get( 0 ) ) {
220 if ( result
== 'prev' ) {
221 if( selected
.is( '.suggestions-special' ) ) {
222 result
= context
.data
.$container
.find( '.suggestions-result:last' )
224 result
= selected
.prev();
225 if ( selected
.length
== 0 ) {
226 // we are at the begginning, so lets jump to the last item
227 if ( context
.data
.$container
.find( '.suggestions-special' ).html() != "" ) {
228 result
= context
.data
.$container
.find( '.suggestions-special' );
230 result
= context
.data
.$container
.find( '.suggestions-results div:last' );
234 } else if ( result
== 'next' ) {
235 if ( selected
.length
== 0 ) {
236 // No item selected, go to the first one
237 result
= context
.data
.$container
.find( '.suggestions-results div:first' );
238 if ( result
.length
== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() != "" ) {
239 // No suggestion exists, go to the special one directly
240 result
= context
.data
.$container
.find( '.suggestions-special' );
243 result
= selected
.next();
244 if ( selected
.is( '.suggestions-special' ) ) {
247 result
.length
== 0 &&
248 context
.data
.$container
.find( '.suggestions-special' ).html() != ""
250 // We were at the last item, jump to the specials!
251 result
= context
.data
.$container
.find( '.suggestions-special' );
255 selected
.removeClass( 'suggestions-result-current' );
256 result
.addClass( 'suggestions-result-current' );
258 if ( updateTextbox
) {
259 if ( result
.length
== 0 || result
.is( '.suggestions-special' ) ) {
260 $.suggestions
.restore( context
);
262 context
.data
.$textbox
.val( result
.data( 'text' ) );
263 // .val() doesn't call any event handlers, so
264 // let the world know what happened
265 context
.data
.$textbox
.change();
267 context
.data
.$textbox
.trigger( 'change' );
271 * Respond to keypress event
272 * @param key Integer Code of key pressed
274 keypress: function( e
, context
, key
) {
275 var wasVisible
= context
.data
.$container
.is( ':visible' );
276 var preventDefault
= false;
281 $.suggestions
.highlight( context
, 'next', true );
282 context
.data
.selectedWithMouse
= false;
284 $.suggestions
.update( context
, false );
286 preventDefault
= true;
291 $.suggestions
.highlight( context
, 'prev', true );
292 context
.data
.selectedWithMouse
= false;
294 preventDefault
= wasVisible
;
298 context
.data
.$container
.hide();
299 $.suggestions
.restore( context
);
300 $.suggestions
.cancel( context
);
301 context
.data
.$textbox
.trigger( 'change' );
302 preventDefault
= wasVisible
;
306 context
.data
.$container
.hide();
307 preventDefault
= wasVisible
;
308 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
309 if ( selected
.size() == 0 || context
.data
.selectedWithMouse
) {
310 // if nothing is selected OR if something was selected with the mouse,
311 // cancel any current requests and submit the form
312 $.suggestions
.cancel( context
);
313 context
.config
.$region
.closest( 'form' ).submit();
314 } else if ( selected
.is( '.suggestions-special' ) ) {
315 if ( typeof context
.config
.special
.select
== 'function' ) {
316 context
.config
.special
.select
.call( selected
, context
.data
.$textbox
);
319 if ( typeof context
.config
.result
.select
== 'function' ) {
320 $.suggestions
.highlight( context
, selected
, true );
321 context
.config
.result
.select
.call( selected
, context
.data
.$textbox
);
323 $.suggestions
.highlight( context
, selected
, true );
328 $.suggestions
.update( context
, true );
331 if ( preventDefault
) {
333 e
.stopImmediatePropagation();
337 $.fn
.suggestions = function() {
339 // Multi-context fields
340 var returnValue
= null;
341 var args
= arguments
;
343 $(this).each( function() {
345 /* Construction / Loading */
347 var context
= $(this).data( 'suggestions-context' );
348 if ( typeof context
== 'undefined' || context
== null ) {
351 'fetch' : function() {},
352 'cancel': function() {},
359 'submitOnClick': false,
360 'maxExpandFactor': 3,
361 'positionFromLeft': true,
362 'highlightInput': false
369 // Handle various calling styles
370 if ( args
.length
> 0 ) {
371 if ( typeof args
[0] == 'object' ) {
372 // Apply set of properties
373 for ( var key
in args
[0] ) {
374 $.suggestions
.configure( context
, key
, args
[0][key
] );
376 } else if ( typeof args
[0] == 'string' ) {
377 if ( args
.length
> 1 ) {
378 // Set property values
379 $.suggestions
.configure( context
, args
[0], args
[1] );
380 } else if ( returnValue
== null ) {
381 // Get property values, but don't give access to internal data - returns only the first
382 returnValue
= ( args
[0] in context
.config
? undefined : context
.config
[args
[0]] );
389 if ( typeof context
.data
== 'undefined' ) {
391 // ID of running timer
393 // Text in textbox when suggestions were last fetched
395 // Number of results visible without scrolling
397 // Suggestion the last mousedown event occured on
398 'mouseDownOn': $( [] ),
400 'selectedWithMouse': false
402 // Setup the css for positioning the results box
404 'top': Math
.round( context
.data
.$textbox
.offset().top
+ context
.data
.$textbox
.outerHeight() ),
405 'width': context
.data
.$textbox
.outerWidth(),
408 if ( context
.config
.positionFromLeft
) {
409 newCSS
['left'] = context
.config
.$region
.offset().left
;
410 newCSS
['right'] = 'auto';
412 newCSS
['left'] = 'auto';
413 newCSS
['right'] = $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
416 context
.data
.$container
= $( '<div />' )
418 .addClass( 'suggestions' )
420 $( '<div />' ).addClass( 'suggestions-results' )
421 // Can't use click() because the container div is hidden when the textbox loses focus. Instead,
422 // listen for a mousedown followed by a mouseup on the same div
423 .mousedown( function( e
) {
424 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results div' );
426 .mouseup( function( e
) {
427 var $result
= $( e
.target
).closest( '.suggestions-results div' );
428 var $other
= context
.data
.mouseDownOn
;
429 context
.data
.mouseDownOn
= $( [] );
430 if ( $result
.get( 0 ) != $other
.get( 0 ) ) {
433 $.suggestions
.highlight( context
, $result
, true );
434 context
.data
.$container
.hide();
435 if ( typeof context
.config
.result
.select
== 'function' ) {
436 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
);
438 context
.data
.$textbox
.focus();
442 $( '<div />' ).addClass( 'suggestions-special' )
443 // Can't use click() because the container div is hidden when the textbox loses focus. Instead,
444 // listen for a mousedown followed by a mouseup on the same div
445 .mousedown( function( e
) {
446 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
448 .mouseup( function( e
) {
449 var $special
= $( e
.target
).closest( '.suggestions-special' );
450 var $other
= context
.data
.mouseDownOn
;
451 context
.data
.mouseDownOn
= $( [] );
452 if ( $special
.get( 0 ) != $other
.get( 0 ) ) {
455 context
.data
.$container
.hide();
456 if ( typeof context
.config
.special
.select
== 'function' ) {
457 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
);
459 context
.data
.$textbox
.focus();
461 .mousemove( function( e
) {
462 context
.data
.selectedWithMouse
= true;
463 $.suggestions
.highlight(
464 context
, $( e
.target
).closest( '.suggestions-special' ), false
468 .appendTo( $( 'body' ) );
470 // Stop browser autocomplete from interfering
471 .attr( 'autocomplete', 'off')
472 .keydown( function( e
) {
473 // Store key pressed to handle later
474 context
.data
.keypressed
= ( e
.keyCode
== undefined ) ? e
.which
: e
.keyCode
;
475 context
.data
.keypressedCount
= 0;
477 switch ( context
.data
.keypressed
) {
478 // This preventDefault logic is duplicated from
479 // $.suggestions.keypress(), which sucks
482 e
.stopImmediatePropagation();
487 if ( context
.data
.$container
.is( ':visible' ) ) {
489 e
.stopImmediatePropagation();
493 .keypress( function( e
) {
494 context
.data
.keypressedCount
++;
495 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
497 .keyup( function( e
) {
498 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
499 // keypress in between, solve it
500 if ( context
.data
.keypressedCount
== 0 ) {
501 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
505 // When losing focus because of a mousedown
506 // on a suggestion, don't hide the suggestions
507 if ( context
.data
.mouseDownOn
.length
> 0 ) {
510 context
.data
.$container
.hide();
511 $.suggestions
.cancel( context
);
514 // Store the context for next time
515 $(this).data( 'suggestions-context', context
);
517 return returnValue
!== null ? returnValue
: $(this);