GithubHelp home page GithubHelp logo

twitter / typeahead.js Goto Github PK

View Code? Open in Web Editor NEW
16.5K 554.0 3.2K 2.1 MB

typeahead.js is a fast and fully-featured autocomplete library

Home Page: http://twitter.github.io/typeahead.js/

License: MIT License

JavaScript 97.36% Shell 0.10% HTML 2.54%

typeahead.js's Introduction

build status Built with Grunt

Inspired by twitter.com's autocomplete search functionality, typeahead.js is a flexible JavaScript library that provides a strong foundation for building robust typeaheads.

The typeahead.js library consists of 2 components: the suggestion engine, Bloodhound, and the UI view, Typeahead. The suggestion engine is responsible for computing suggestions for a given query. The UI view is responsible for rendering suggestions and handling DOM interactions. Both components can be used separately, but when used together, they can provide a rich typeahead experience.

Getting Started

How you acquire typeahead.js is up to you.

Preferred method:

  • Install with Bower: $ bower install typeahead.js

Other methods:

Note: both bloodhound.js and typeahead.jquery.js have a dependency on jQuery 1.9+.

Documentation

Examples

For some working examples of typeahead.js, visit the examples page.

Browser Support

  • Chrome
  • Firefox 3.5+
  • Safari 4+
  • Internet Explorer 8+
  • Opera 11+

NOTE: typeahead.js is not tested on mobile browsers.

Customer Support

For general questions about typeahead.js, tweet at @typeahead.

For technical questions, you should post a question on Stack Overflow and tag it with typeahead.js.

Issues

Discovered a bug? Please create an issue here on GitHub!

https://github.com/twitter/typeahead.js/issues

Versioning

For transparency and insight into our release cycle, releases will be numbered with the following format:

<major>.<minor>.<patch>

And constructed with the following guidelines:

  • Breaking backwards compatibility bumps the major
  • New additions without breaking backwards compatibility bumps the minor
  • Bug fixes and misc changes bump the patch

For more information on semantic versioning, please visit http://semver.org/.

Testing

Tests are written using Jasmine and ran with Karma. To run the test suite with PhantomJS, run $ npm test.

Developers

If you plan on contributing to typeahead.js, be sure to read the contributing guidelines. A good starting place for new contributors are issues labeled with entry-level. Entry-level issues tend to require minor changes and provide developers a chance to get more familiar with typeahead.js before taking on more challenging work.

In order to build and test typeahead.js, you'll need to install its dev dependencies ($ npm install) and have grunt-cli installed ($ npm install -g grunt-cli). Below is an overview of the available Grunt tasks that'll be useful in development.

  • grunt build – Builds typeahead.js from source.
  • grunt lint – Runs source and test files through JSHint.
  • grunt watch – Rebuilds typeahead.js whenever a source file is modified.
  • grunt server – Serves files from the root of typeahead.js on localhost:8888. Useful for using test/playground.html for debugging/testing.
  • grunt dev – Runs grunt watch and grunt server in parallel.

Maintainers

Authors

License

Copyright 2013 Twitter, Inc.

Licensed under the MIT License

typeahead.js's People

Contributors

adardesign avatar akre54 avatar alecrust avatar antonpalyok avatar aronwoost avatar asafary avatar caniszczyk avatar daraosn avatar davidxi avatar dr3x avatar evverx avatar gintsmurans avatar isaachaze avatar jaspertey avatar jeffmax avatar jharding avatar jlbooker avatar jmwong avatar lamberta avatar lookfirst avatar morgon avatar mutewinter avatar noidontdig avatar pokehanai avatar ragulka avatar ritey avatar simonexmachina avatar stevenwilkin avatar timtrueman avatar twhitbeck avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typeahead.js's Issues

Group by categories

Anyway to group results by categories? It would be nice to show the category name and list the items below it.

Problem with remote url datasets

Hi guys, I started to try the library today, and testing with a simple remote dataset, I came with this jquery error:

TypeError: invalid 'in' operand e

After a quick check, I realized that the error is triggering on the onSuccess callback of the ajax call of the get method, this line:

cb && cb(resp);

I'm missing something? Working with jquery 1.9.1 and typeahead.js,

Placeholder displaced on backspace

Hi,

I found a litte problem with the placeholder when deleting letters from selection.
To reproduce:

  1. demopage -> countries
  2. type "ge"
  3. select 3rd option "South Georgia and the South Sandwich Islands"
  4. hit backspace for deleting last "s"

Now the placeholder is visible in the back and is aligned left, while the input is aligned right.

typeahead_placeholder_displacement

regards

Allow accessing remote data when suggestion data is nested..

We have data coming back from the server that looks as follows...


{
    "status": "success",
    "keyword": "s",
    "data": {
        "suggestions": [
           {
             value: 'unitedAirlines',
             tokens: ['united', 'airlines'],
             name: 'Jake Harding',
        },
           {
             value: 'deltaAirlines',
             tokens: ['delta', 'airlines'],
             name: 'Jake Harding',
        }
    }
}

The question is how to I tell typeahead.js to get the suggestions data.

Add Suggestions Title

I'td be nice if we could define a "headline" to be displayed on top of the suggestions list.
I.e. "Top matches". For example Apple has little headings ("Common Searches" and "Recommended Results") in their suggestions which you can see in the attached screenshot.
apple-prefetch

Add callbacks to template, remote and an onSelection event

Can we have a callback function for template ? I had something like this in mind:

template: function(datum)  {
    if( datum.isCustomer )
         return '<p class="someClass">Customer: ' + datum.customer + '</p>';
    else
         return 'Nope...';
}

This would allow the use of "if/else/while/for" and other conditional statement to render the results.

The same would be awesome for an "onSelection" event:

onSelection: function(datum)  {
    if( datum.isCustomer )
         alert(datum.customer + ' has been selected !');
    else
         alert('Something else has been selected my son !');
}

Finally, if we could provide a function for the remote option, it would allow us to use our own way to send the AJAX request. Let's say:

remote: function()  {
    var jsonResult = mySuperAjaxLibrary.send('http://ajax.somesupersite.net/search.php');

    return jsonResult;
}

If you make this happen, I love will you forever.

Thank you and pardon my poor english.

Suggestion: Setting to change "value" key

Use case: I am using an existing API to fetch data for the typeahead. The data from the API does not contain a key called "value". It does however have another meaningful key called "name" I would like to use.

Suggestion: To have a property where we can set the value key, so we do not have to write wrappers for existing API's.

$(element).typeahead([{
    name: 'source1',
    remote: '/api/search?q=%QUERY',
    valueKey: 'name'
}]);

Space wildcard

I know that is not a real issue because the tokens must not be formatted this way.
But anyway,

{
 value: "test",
 tokens: [
   'test', 'foo', '', 'bar'
  ]
}

Situation
The tokens are setted, but there is an empty key in it

Action
user click for the first time in the input, nothing bad happen
user type something, backspace everything until no letter left

Result
all "" token are matched, placeholder is displayed again but above the autocompletion.
And now everytime the user click(focus) in the input, the autocompletion is shown.

Again, it's a mistake made by the developper (me in this case) so it's not a real issue but it could also be an intersting wildcard if it was displayed on the first click and without the placeholder bug :)

Input value blank on blur

Go to the example demo page,

$('input[placeholder="countries"]').val('France').click().blur(); the input value is now blank.

If you set a value, you would like to keep it no ? (I would)

Same problem if the input contains a value before becoming a typeahead input.

Trigger custom events

There's a handful of issues asking for something along the lines of a "selection callback". While I agree this is necessary, I don't think adding an option like onSelection is the best way to go about it. Instead, I think triggering custom events on the typeahead input is the way to go. It's a more extensible approach and it won't pollute the options hash.

I'm creating this ticket to start brainstorming what events we need to trigger. The only 2 I can think of right now are:

  • suggestion selected (#22)
  • prefetched data loaded (#64)

If there's anything else you'd like an event triggered for, leave a comment in this issue.

allow option to initialize only on interacting

Currently this plugin runs and initializes as soon as its called, even if the input was never interacted with, This adds overhead for memory etc.

How about allowing the option initializeOn:"keypress" which will all initializing functionality only upon provided (optional) option.

This way users has full control on initializing only on first interaction (how the user wants to define that)

Currently, this can be achieved as following:

$("#inputEle").one(function("input"){
     $("#inputEle").typeahead(options).trigger("input");

});

remote data rendering problem

Hi guys, I've a strange problem with rendering the template for my remote data (I'm using Hogan).

Let's say I have this JSON data returned from the server:

var data={"companies": [{"id": "1", "name": "Twitter", "value": "twitter"}, {"id": "2", "name": "Facebook", "value": "facebook"}]}

And I have this template:

var text="{{#companies}}{{name}}{{/companies}}{{^companies}}'No companies!'{{/companies}}"

If I run Hogan within the browser console, it renders the data correctly:

tpl=Hogan.compile(text)
tpl.render(data)
=> "TwitterFacebook"

BUT if I use typeahead, with the same template and Hogan as the engine, it gives me "No companies!" and no completion.

$("input[name='query']").typeahead({
    name: 'search',
    remote: '/search.json?query=%QUERY',
    template: [
      '{{#companies}}',
        '{{name}}',
      '{{/companies}}',
      '{{^companies}}',
        'No companies!',
      '{{/companies}}'
    ].join(''),
    engine: Hogan
  })

To be sure that typeahead is working, I returned a plain datum array and changed the template accordingly:

{
  "name": "Twitter",
  "value": "twitter"
}
{
  "name": "Facebook",
  "value": "facebook"
}

and it worked good, giving me result list and completion.

What I'm missing?

Typeahead is using old data(wont update)

Updated the my data (.json) with new data, but it still uses the old data if I enter somethign in the search, and if I change the js code it will stop working and give me an syntax error in the jquery core. I cleared the cache a couple of times but it wont work.

I am using it in firefox and local.

wrapInput sets incorrect autocomplete attrib

A typeahead input is wrapped with some additional markup by this code:

return $input.attr({
  autocomplete: false,
  spellcheck: false
}).addClass("tt-query").wrap(html.wrapper).parent().prepend($hint).append(html.dropdown);

The boolean false values are converted to the string "false" by jQuery. However, Chrome and Safari (and perhaps other browsers as well) will still autocomplete on the field, because the autocomplete attribute actually should be set to the string "off" per spec.

The same problem with this attribute occurs on the tt-hint input's markup.

Plans to support jQuery-compatible libraries?

Currently, it looks like typeahead.js has a hard dependency on jQuery. Are there any specific reasons that this is the case, or is it reasonable to assume that one might be able to use something like Zepto in the future instead?

If the latter, are there any plans for doing so presently?

Xss issue

Script gets executed when given as an option
$('#sampleauto').typeahead({
name: 'accounts',
local: ['github', 'select2', 'typeahead', '<script>alert("github")</script>']
});

Can't find a datum with a token containing a dash

The following datum won't be found when typing 'course-106' into typeahead:

{
label: "Course-106: Twitter Typeahead"
value: "course106",
tokens: [
   "course-106:",
   "twitter",
   "typeahead"
]

But it appears that one could customize the tokenizeText function to support this:

tokenizeText: function(str) {
          //return $.trim(str).toLowerCase().split(/[\s\-_]+/);
            return $.trim(str).toLowerCase().split(/[\s_]+/);
        }

Consider adding a configuration option so that users can provide customized regular expression for tokenizedText unless there's a better solution.

Plugin doesnt inherite input:focus css (background)

This wrecked my head all day yesterday. My textbox has a background which changes on focus. Typeahead doesnt inherite this when it creates .tt-hint and I couldnt fix it in css because there is no before sibling selector in css. Eventually I just wrote the solution with jQuery.

        $(function(){

            $(".tt-query").focus(function(){
                $(".tt-hint").addClass('focusclass');
            }).blur(function(){
                $(".tt-hint").removeClass('focusclass');
            });

        });
  .focusclass { background: #f5f5f5 !important; -webkit-box-shadow: none; -moz-box-shadow: none; -ms-box-shadow: none; box-shadow: none; }

Should default suggestions be supported?

When typeaheads gain focus and no query has been entered yet, should we support default top suggestions? I could see how this could be useful.

You can sort of do this with the current implementation of typeahead.js by using '' as a token. It's a little buggy though because the hint is shown and it overlaps with the placeholder.

Allow remote to be a callback

If the remote returns something where the dataset is nested, you can't extract the dataset from it. It would also allow to customise the call to the backend if some extra headers were to be set.

Autocompletion starting with Uppercase Letter

When the dalatist present some word starting by an upper case letter, the user type in lowercase and complete it with tab, the first letter will not be changed but the rest of the word is still well completed (I mean with upper case)

ie:
data given = Coca-Cola
data typed = co

user do tab

data displayed = coca-Cola

Don't know if it's a real issue but it's a bit annoying. Doesn't occur with other shortcut.

Warn users of serving static json files with nginx

I was trying out the examples where a json is prefetched, so I first tried a static json file served with nginx. I got the error:

"Uncaught TypeError: Cannot use 'in' operator to search for '123' in"

It turns out that the default nginx configuration doesn't send a correct json type.

Adding

 application/json                json; 

to mime.types of nginx solved the problem.

I am not sure whether this is a bug in nginx, jquery or typeahead, but just wanted to document it in case someone else comes across this.

A sample project that demonstrates the bug is here: https://dl.dropbox.com/u/83342/nginxbug.zip

Bower – how do I use you?

Since typeahead.js is generated from the files in src/ and isn't checked in, how are we supposed to define our Bower component? Do we need a shim repo? Do we just bite the bullet and check in typeahead.js (I'd rather not)?

@sindresorhus, any suggestions?

Option for Automatic selection of the first item in the typeahead resultset

Would it be possible for there to be an option for the first item to be automatically selected in the typeahead on search so a press of the enter key will go to that specific item's url? This would save the user needing to press the downarrow key to get to that first item and then pressing the enter key. Thanks!

Adding ability to trigger callbacks on selection/click of dropdown.

Maybe you can do this now, but I have been looking at it for a few hours .... I would like to integrate this search bar into a dashboard I have that is rendering a series of results via backbone.js. I have it working now, but it would be nice to provide a callback to type to do the filter on: click, dropdown, etc.

remote call depends on another value

Hi !
Could remote call url depends on another value, such as another input field value ?
It works once, but then the url doesn't change on that value change.
Thanks a lot !

Same data (simple string array) works with remote and local, but not with prefetch

Hi !
Same data (simple string array) works with remote and local, but not with prefetch.

["Corse","Alsace","Vall\u00e9e de la Loire","Jura \/ Savoie","Provence","Languedoc - Roussillon","Beaujolais","Sud Ouest","Bourgogne","Bordeaux","Champagne","Vall\u00e9e du Rh\u00f4ne"]

JS error in isArray, in jquery.min.js.
TypeError: invalid 'in' operand e

Using JQuery 1.9.1

Any idea ? Thanks !

Add default template engine

I was a bit surprised to see the lack of a default template engine. I know you can add an extra dependency on handlebars or so.

Maybe a good start:

element.typeahead(
        template: '<p>$name ($code)</p>',
        remote: '/api?value=%QUERY',
        engine:
          compile: (template) ->
            return {
              render: (ctx)->
                return template.replace(/\$(\w+)/g,
                  (msg) -> ctx[msg.substring(1)]
                )
            }
      )

General callback for when typeahead is fully initialized and ready

I'd appreciate a general callback so i can find out when typeahead is initialized and done prefetching etc.

For example:

$("input").typeahead({
  name: 'description', 
  prefetch: 'search.json',
  limit: 1000,
  callback: function(){
    alert("Typeahead is ready for you!");
  }
});

how to re-initialize typeahead

What is the recommended approach for re-initializing typeahead to change a prefetch, a dataset, or some other property?

Breaks up/down keys with modifiers

Because of preventDefault, shift-up/down don't properly highlight and select input text, and alt/cmd-up/down don't properly let the cursor move to the beginning and end of the field.

Add highlighting

Maybe something similar to what Bootstrap's typeahead offers.

Selection callback

It would be nice to have a simple way to set a custom callback when a suggested item is selected.

I expect something like:

selectCallback : function(typeaheadItem, selectedItem){ .... }

where

  • typeaheadItem is the text input
  • selectedItem is the suggested item that was selected

This way it would be easier to user other properties/attributes of the selected item (not only the value property) when something is selected.

Template not rendering when it should

Here is my data items returned from server -

[{
    "tokens": ["Python"],
    "name": "Python",
    "value": "python",
    "id": "1"
}, {
    "tokens": ["PHP"],
    "name": "PHP",
    "value": "php",
    "id": "2"
}, {
    "tokens": ["Ruby"],
    "name": "Ruby",
    "value": "ruby",
    "id": "3"
}, {
    "tokens": ["Scala"],
    "name": "Scala",
    "value": "scala",
    "id": "4"
}, {
    "tokens": ["HTML"],
    "name": "HTML",
    "value": "html",
    "id": "5"
}, {
    "tokens": ["HTML5"],
    "name": "HTML5",
    "value": "html5",
    "id": "6"
}, {
    "tokens": ["JavaScript"],
    "name": "JavaScript",
    "value": "javascript",
    "id": "7"
}, {
    "tokens": ["CSS"],
    "name": "CSS",
    "value": "css",
    "id": "8"
}, {
    "tokens": ["CSS3"],
    "name": "CSS3",
    "value": "css3",
    "id": "9"
}]

And initializing like -

<script type="text/javascript" src="{{ STATIC_URL }}js/vendor/hogan-2.0.0.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/vendor/typeahead.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#skills').typeahead([
        {
            name: 'inhouse',
            prefetch: '{% url ajax-skills %}',
            remote: '{% url ajax-skills %}?q=%QUERY',
            template: '<strong>{{id}}</strong>',
            engine: Hogan
        }
    ]);
});
</script>

jQuery has been loaded above these. The problem is, the template option is not being rendered properly. For the above case, all it generates is empty strong elements. and if I don't put any html tag inside the template option, it just takes the value field from the received data and acts on it's own and ignores whatever I've written inside the template field. What is the problem?

PS: And even though I've put all those data in prefetch, it calls the server on every keypress. It shouldn't, right?

Extra network traffic on deleting term

In the best picture winners example, typeahead is configured like this:

$('.example-films .typeahead').typeahead([
  {
    name: 'best-picture-winners',
    remote: '../data/films/queries/%QUERY.json',
    prefetch: '../data/films/post_1960.json',
    template: '<p><strong>{{value}}</strong> – {{year}}</p>',
    engine: Hogan
  }
]);

If I enter "b", it issues a network request to

http://twitter.github.com/typeahead.js/data/films/queries/b.json

for which the response is

[
  {
    "year": "1928/1929",
    "value": "The Broadway Melody",
    "tokens": [
      "The",
      "Broadway",
      "Melody"
    ]
  },
  {
    "year": "1935",
    "value": "Mutiny on the Bounty",
    "tokens": [
      "Mutiny",
      "on",
      "the",
      "Bounty"
    ]
  },
  {
    "year": "1946",
    "value": "The Best Years of Our Lives",
    "tokens": [
      "The",
      "Best",
      "Years",
      "of",
      "Our",
      "Lives"
    ]
  },
  {
    "year": "1957",
    "value": "The Bridge on the River Kwai",
    "tokens": [
      "The",
      "Bridge",
      "on",
      "the",
      "River",
      "Kwai"
    ]
  },
  {
    "year": "1959",
    "value": "Ben-Hur",
    "tokens": [
      "Ben-Hur"
    ]
  }
]

Good.

Now if I delete the 'b' from the input, typeahead issues a request to:

http://twitter.github.com/typeahead.js/data/films/queries/.json

Which comes back with a 404. If there isn't a way to prevent this request, this is a bug.

Suggestion: method to call to programatically search for a and show suggestions

Hi,

i'd appreciate a method i could call, so typeahead would init, pull in the defined json, do the search and present the results.

Currently i do this with a hack: $("input.typeahead").trigger("input");

Some background on why i'd find this useful:
im am trying to use typeahead.js not only for suggestions but for a complete search engine.
My goal is to offer the user suggestions while he types into the input field and then, once hits the return key, i'll load a searchresults page and display a complete list of all matches. The search results page pre populates the input field with from a parameter in the query string, wires the field up with .typeahead and would then need to call a method so typeahead will do its magic and display the results (which i reformat with jquery so they'll not be attached to the input field any longer).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.