Algolia Places is closing. We can help.

Basic autocomplete demo

Introduction #

Get started with a simple autocomplete example.

View live on CodePen

HTML #

            
<html>

    <head>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-theme-classic"/>
    </head>

    <body>

        <div id="search-container"></div>

        <script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-js"></script>
        <script src="/assets/js/app.js"></script>

    </body>
</html>
            
        

CSS #

            
body {
    background: black;
    color: white;
    padding-top: 60px;
}


.algolia-autocomplete {
    width: 100%;
}

.algolia-autocomplete .aa-input,
.algolia-autocomplete .aa-hint {
    width: 100%;
}

.algolia-autocomplete .aa-hint {
    color: #999;
}

.algolia-autocomplete .aa-dropdown-menu {
    width: 100%;
    background-color: #fff;
    border: 1px solid #999;
    border-top: none;
}

.algolia-autocomplete .aa-dropdown-menu .aa-suggestion {
    cursor: pointer;
    padding: 5px 4px;
}

.algolia-autocomplete .aa-dropdown-menu .aa-suggestion.aa-cursor {
    background-color: #20d0f0;
}

.algolia-autocomplete .aa-dropdown-menu .aa-suggestion em {
    font-weight: bold;
    font-style: normal;
}
            
        

JavaScript #

            
const { autocomplete, getAlgoliaResults } = window["@algolia/autocomplete-js"];

const searchClient = algoliasearch(
    "DM340JGS49",
    "YOUR_PLACESAPI_KEY_HERE"
);

autocomplete({
    container: "#search-container",
    detachedMediaQuery: "none",
    placeholder: "Search for places...",
    getSources() {
        return [{
            sourceId: "places",
            getItems({ query }) {
                return getAlgoliaResults({
                    searchClient,
                    queries: [
                        {
                            indexName: "places",
                            query,
                        },
                    ],
                });
            },
            templates: {
                item({ item }) {
                    return `${item.name}, ${item.county}, ${item.country}`;
                },
            },
            onSelect: function (event) {
                event.setQuery(
                    event.item.name + ", " + event.item.county + ", " + event.item.country
                );
            },
        }];
    },
});