Repository: Pixabay/jQuery-autoComplete Branch: master Commit: b9a703e62a7f Files: 6 Total size: 31.3 KB Directory structure: gitextract_in5amcwq/ ├── auto-complete.jquery.json ├── bower.json ├── demo.html ├── jquery.auto-complete.css ├── jquery.auto-complete.js └── readme.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: auto-complete.jquery.json ================================================ { "name": "auto-complete", "title": "autoComplete", "description": "An extremely lightweight completion suggester plugin for jQuery.", "version": "1.0.7", "dependencies": { "jquery": ">=1.7" }, "keywords": [ "autocomplete", "suggest", "autosuggest", "suggester", "jQuery" ], "author": { "name": "Simon Steinberger", "url": "https://pixabay.com/users/Simon/", "email": "simon@pixabay.com" }, "licenses": [ { "type": "MIT", "url": "http://www.opensource.org/licenses/mit-license.php" } ], "homepage": "https://goodies.pixabay.com/jquery/auto-complete/demo.html", "demo": "https://goodies.pixabay.com/jquery/auto-complete/demo.html" } ================================================ FILE: bower.json ================================================ { "name": "jquery-auto-complete", "description": "A lightweight autocomplete plugin for jQuery.", "version": "1.0.7", "dependencies": { "jquery": ">=1.7" }, "homepage": "https://github.com/Pixabay/jQuery-autoComplete", "authors": [{ "name": "Simon Steinberger", "url": "https://pixabay.com/users/Simon/", "email": "simon@pixabay.com" }], "keywords": [ "autocomplete", "autosuggest", "autosuggester", "suggest", "suggester", "completer", "select", "dropdown", "ajax" ], "licenses": [{ "type": "MIT", "url": "http://www.opensource.org/licenses/mit-license.php" }], "ignore": [ "bower.json", "demo.html", "auto-complete.jquery.json", "readme.md" ] } ================================================ FILE: demo.html ================================================ jQuery autoComplete Plugin

autoComplete

An extremely lightweight completion suggester plugin for jQuery.

Download   View on GitHub

Overview and Features

Released under the MIT License. Source on Github (changelog). Compatible with jQuery 1.7.0+ in Firefox, Safari, Chrome, Opera, Internet Explorer 7+. No dependencies except the jQuery library.

This plugin was developed by and for Pixabay.com - an international repository for free Public Domain images. We have implemented this piece of software in production and we share it - in the spirit of Pixabay - freely with others.

Why another jQuery autocomplete plugin?

This plugin is largely based on DevBridge's wonderful Ajax AutoComplete. We used this autocompleter for several weeks on Pixabay and it worked nicely. However, we ended up hacking more and more into the original code - changing keyboard navigation and AJAX requests. Finally, we decided to go for an own, ultra lightweight plugin code that is perfectly optimized for our needs. And here we are ...

Usage

Include the stylesheet jquery.auto-complete.css in the <head> section of your page - and the JavaScript file jquery.auto-complete.min.js after loading the jQuery library. autoComplete accepts settings from an object of key/value pairs, and can be assigned to any text input field.

$(selector).autoComplete({key1: value1, key2: value2});

Settings

PropertyDefaultDescription
source(term, response)null Required callback function to connect any data source to autoComplete. The callback gets two arguments:
  • term, which refers to the value currently in the text input.
  • A response callback, which expects a single argument: the data to suggest to the user. This data must be an array of filtered suggestions based on the provided term:
    ['suggestion 1', 'suggestion 2', 'suggestion 3', ...]
minChars3Minimum number of characters (>=1) a user must type before a search is performed.
delay150The delay in milliseconds between when a keystroke occurs and when a search is performed. A zero-delay is more responsive, but can produce a lot of load.
cachetrueDetermines if performed searches should be cached.
menuClass'' Custom class/es that get/s added to the dropdown menu container.
Example: { menuClass: 'class1 class2' }
renderItemfunction

A function that gives you control over how suggestions are displayed. Default:

function (item, search){
    search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
    return '<div class="autocomplete-suggestion" data-val="' + item + '">'\
        + item.replace(re, "<b>$1</b>") + '</div>';
}
 
Callbacks
onSelect(event, term, item) A callback function that fires when a suggestion is selected by mouse click, enter, or tab. event is the event that triggered the callback, term is the selected value. and item is the item rendered by the renderItem function.
 
Public Methods
destroyRemoves the autoComplete instance and its bindings.

Demos

Searching in local data

This plugin was designed mainly with AJAX requests in mind, but it may be used with local data, as well. Connecting the autocompletion suggester to an array of strings can be done in the source function like so:

$('input[name="q"]').autoComplete({
    minChars: 2,
    source: function(term, suggest){
        term = term.toLowerCase();
        var choices = ['ActionScript', 'AppleScript', 'Asp', ...];
        var matches = [];
        for (i=0; i<choices.length; i++)
            if (~choices[i].toLowerCase().indexOf(term)) matches.push(choices[i]);
        suggest(matches);
    }
});

The source function iterates through an array of (local) choices and we return a new array containing all (lowercased) matches. Simple as that.

AJAX requests

AJAX requests may come with very different requirements: JSON, JSONP, GET, POST, additionaly params, authentications, etc. In order to keep the source code small while retaining full flexibility, we decided to only use a simple callback function as the source for suggestions. Make your AJAX call inside this function and return matching suggestions with the response callback:

$('input[name="q"]').autoComplete({
    source: function(term, response){
        $.getJSON('/some/ajax/url/', { q: term }, function(data){ response(data); });
    }
});

The AJAX call in this example needs to return an array of strings. The callback response must always be called, even if no suggestions are returned or if an error occured. This ensures the correct state of the autoComplete instance.

Optimizing AJAX requests

All search results are cached by default and unnecessary requests are prevented in order to keep server load as low as possible. To further reduce server impact, it's possible to abort unfinished AJAX requests before starting new ones:

var xhr;
$('input[name="q"]').autoComplete({
    source: function(term, response){
        try { xhr.abort(); } catch(e){}
        xhr = $.getJSON('/some/ajax/url/', { q: term }, function(data){ response(data); });
    }
});

By typing along, the user may trigger one AJAX request after the other. With this little trick, we make sure that only the most current one actually gets executed - if not done so already.

Advanced suggestions handling and custom layout

By making use of the renderItem() function, it's possible to turn the autocompleter into an item suggester:

While typing country names or language codes, a list of matching suggestions is displayed. E.g. typing "de" will show "Germany" as a suggestion, because "de" is the language code for German. Source code for this example:

$('input[name="q"]').autoComplete({
    minChars: 1,
    source: function(term, suggest){
        term = term.toLowerCase();
        var choices = [['Australia', 'au'], ['Austria', 'at'], ['Brasil', 'br'], ...];
        var suggestions = [];
        for (i=0;i<choices.length;i++)
            if (~(choices[i][0]+' '+choices[i][1]).toLowerCase().indexOf(term)) suggestions.push(choices[i]);
        suggest(suggestions);
    },
    renderItem: function (item, search){
        search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
        var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
        return '<div class="autocomplete-suggestion" data-langname="'+item[0]+'" data-lang="'+item[1]+'" data-val="'+search+'"><img src="img/'+item[1]+'.png"> '+item[0].replace(re, "<b>$1</b>")+'</div>';
    },
    onSelect: function(e, term, item){
        alert('Item "'+item.data('langname')+' ('+item.data('lang')+')" selected by '+(e.type == 'keydown' ? 'pressing enter' : 'mouse click')+'.');
    }
});

In this case, autocompleting the text field is not desired, so we turn it off by setting data-val="'+search+'" in the renderItem() function. However, when choosing an item, the onSelect() callback returns all required information.

Please report any bugs and issues at the GitHub repositiory.

This software is released as Open Source under the MIT License by Simon Steinberger / Pixabay.com.

About Us Blog More Goodies © Pixabay.com / Simon Steinberger / Hans Braxmeier
================================================ FILE: jquery.auto-complete.css ================================================ .autocomplete-suggestions { text-align: left; cursor: default; border: 1px solid #ccc; border-top: 0; background: #fff; box-shadow: -1px 1px 3px rgba(0,0,0,.1); /* core styles should not be changed */ position: absolute; display: none; z-index: 9999; max-height: 254px; overflow: hidden; overflow-y: auto; box-sizing: border-box; } .autocomplete-suggestion { position: relative; padding: 0 .6em; line-height: 23px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 1.02em; color: #333; } .autocomplete-suggestion b { font-weight: normal; color: #1f8dd6; } .autocomplete-suggestion.selected { background: #f0f0f0; } ================================================ FILE: jquery.auto-complete.js ================================================ /* jQuery autoComplete v1.0.7 Copyright (c) 2014 Simon Steinberger / Pixabay GitHub: https://github.com/Pixabay/jQuery-autoComplete License: http://www.opensource.org/licenses/mit-license.php */ (function($){ $.fn.autoComplete = function(options){ var o = $.extend({}, $.fn.autoComplete.defaults, options); // public methods if (typeof options == 'string') { this.each(function(){ var that = $(this); if (options == 'destroy') { $(window).off('resize.autocomplete', that.updateSC); that.off('blur.autocomplete focus.autocomplete keydown.autocomplete keyup.autocomplete'); if (that.data('autocomplete')) that.attr('autocomplete', that.data('autocomplete')); else that.removeAttr('autocomplete'); $(that.data('sc')).remove(); that.removeData('sc').removeData('autocomplete'); } }); return this; } return this.each(function(){ var that = $(this); // sc = 'suggestions container' that.sc = $('
'); that.data('sc', that.sc).data('autocomplete', that.attr('autocomplete')); that.attr('autocomplete', 'off'); that.cache = {}; that.last_val = ''; that.updateSC = function(resize, next){ that.sc.css({ top: that.offset().top + that.outerHeight(), left: that.offset().left, width: that.outerWidth() }); if (!resize) { that.sc.show(); if (!that.sc.maxHeight) that.sc.maxHeight = parseInt(that.sc.css('max-height')); if (!that.sc.suggestionHeight) that.sc.suggestionHeight = $('.autocomplete-suggestion', that.sc).first().outerHeight(); if (that.sc.suggestionHeight) if (!next) that.sc.scrollTop(0); else { var scrTop = that.sc.scrollTop(), selTop = next.offset().top - that.sc.offset().top; if (selTop + that.sc.suggestionHeight - that.sc.maxHeight > 0) that.sc.scrollTop(selTop + that.sc.suggestionHeight + scrTop - that.sc.maxHeight); else if (selTop < 0) that.sc.scrollTop(selTop + scrTop); } } } $(window).on('resize.autocomplete', that.updateSC); that.sc.appendTo('body'); that.sc.on('mouseleave', '.autocomplete-suggestion', function (){ $('.autocomplete-suggestion.selected').removeClass('selected'); }); that.sc.on('mouseenter', '.autocomplete-suggestion', function (){ $('.autocomplete-suggestion.selected').removeClass('selected'); $(this).addClass('selected'); }); that.sc.on('mousedown click', '.autocomplete-suggestion', function (e){ var item = $(this), v = item.data('val'); if (v || item.hasClass('autocomplete-suggestion')) { // else outside click that.val(v); o.onSelect(e, v, item); that.sc.hide(); } return false; }); that.on('blur.autocomplete', function(){ try { over_sb = $('.autocomplete-suggestions:hover').length; } catch(e){ over_sb = 0; } // IE7 fix :hover if (!over_sb) { that.last_val = that.val(); that.sc.hide(); setTimeout(function(){ that.sc.hide(); }, 350); // hide suggestions on fast input } else if (!that.is(':focus')) setTimeout(function(){ that.focus(); }, 20); }); if (!o.minChars) that.on('focus.autocomplete', function(){ that.last_val = '\n'; that.trigger('keyup.autocomplete'); }); function suggest(data){ var val = that.val(); that.cache[val] = data; if (data.length && val.length >= o.minChars) { var s = ''; for (var i=0;i= o.minChars) { if (val != that.last_val) { that.last_val = val; clearTimeout(that.timer); if (o.cache) { if (val in that.cache) { suggest(that.cache[val]); return; } // no requests if previous suggestions were empty for (var i=1; i' + item.replace(re, "$1") + ''; }, onSelect: function(e, term, item){} }; }(jQuery)); ================================================ FILE: readme.md ================================================ jQuery-autoComplete =================== An extremely lightweight completion suggester plugin for jQuery. Compatible with jQuery 1.7.0+ in Firefox, Safari, Chrome, Opera, Internet Explorer 7+. No dependencies except the jQuery library. Released under the MIT License: http://www.opensource.org/licenses/mit-license.php This plugin was developed by and for [Pixabay.com](https://pixabay.com/) - an international repository for sharing free public domain images. We have implemented this plugin in production and we share this piece of software - in the spirit of Pixabay - freely with others. ## Demo and Documentation https://goodies.pixabay.com/jquery/auto-complete/demo.html ## Features * Lightweight: 3.4 kB of JavaScript - less than 1.4 kB gzipped * Fully flexible data source * Smart caching, delay and minimum character settings * Callbacks ## Changelog ### Version 1.0.7 - 2015/08/15 * Fixed #29: Select item with tab. * Fixed #33: Suggestions not hidden on fast input. * Fixed incorrect selection by mouse when suggestions are scrolled down. ### Version 1.0.6 - 2015/04/22 * Fixed #7: Firing onSelect callback on enter and passing event and selected suggestion item as additional arguments. ### Version 1.0.5 - 2014/11/26 * Fixed #4: renderItem bugfix ### Version 1.0.4 - 2014/11/26 * Added renderItem function options allowing custom data passing and autoComplete rendering (https://github.com/Pixabay/jQuery-autoComplete/pull/3). * Improved auto positioning. ### Version 1.0.3 - 2014/11/17 * Added menuClass option for custom styling multiple autoComplete dropdowns on one page. * Fixed destroy method. ### Version 1.0.2 - 2014/09/13 * Another fix of the auto-positioning method on init. ### Version 1.0.1 - 2014/08/10 * Fixed auto positioning of suggestions container on init. ### Version 1.0.0-beta - 2014/07/15 * First release