typeahead demo

Googleのオートコンプリート機能のようなものを気軽に実装

by iwbjp

HTML

<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.js"></script>
<input type="text" class="typeahead" id="search">

CSS

html {
    font-family: "Helvetica Neue", "Arial", sans-serif;
    font-size: 14px;
    line-height: 1.29;
}
.typeahead,
.tt-query,
.tt-hint {
    font-family: inherit;
    width: 396px;
    padding: 8px 12px;
    font-size: 24px;
    line-height: 30px;
    border: 2px solid #ccc;
    border-radius: 8px;
    outline: none;
}
.typeahead {
    background-color: #fff;
}
.typeahead:focus {
    border-color: #0097cf;
}
.tt-query {
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
    color: #999
}
.tt-dropdown-menu {
    width: 422px;
    margin-top: 12px;
    padding: 8px 0;
    background-color: #fff;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    border-radius: 8px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.tt-suggestion {
    padding: 3px 20px;
    font-size: 18px;
    line-height: 24px;
}
.tt-suggestion.tt-is-under-cursor {
    color: #fff;
    background-color: #0097cf;
}
.tt-suggestion p {
    margin: 0;
}

JavaScript

var arr = [];
$.ajax({
    type: 'GET',
    url: 'http://stat100.ameba.jp/amesta/mypageAmestaTitleList.json',
    dataType: 'jsonp',
    jsonp   : 'jsoncallback',
    jsonpCallback   : 'amesta',
    success : function(json){
        var jsonLen = json.info.length;
        
        for(var i=0; i<jsonLen; i++){
            console.log(json.info[i].title);
            arr[i] = json.info[i].title;
        }
        $('#search').typeahead({
            local: arr
        });
    }
});