Search system with algolia part#2 Use Autocomplete.js, Connect algolia with autocomplete.js, and Display Suggestions

in #utopian-io6 years ago (edited)

Repository

https://github.com/Algolia

What Will I Learn?

  • Use Autocomplete.js
  • Connect algolia with autocomplete.js
  • Display Suggestions

Resources

Difficulty

Intermediated

Tutorial Content

This tutorial is a continuation tutorial from the previous search system tutorial, in this tutorial, we will combine algolia with autocomplete.js so that the search system we make is better and makes it easier for users to search our system. we will give suggestions to users based on keywords that the user type. for more details, just start our tutorial.

Use Autocomplete.js

I will use Autocomplete.js, this library is provided by algolia. Autocomplete focuses on the frontend, even though it is given by algolia, it can be used stand-alone, jquery, and angular.js for more details you can see on their GitHub page https://github.com/algolia/autocomplete.js. but in this tutorial, I will use it with Jquery, to use it in Jquery you can see it as follows:

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Duski Tutor</title>
<script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>
</head>
<body>
    <h1>Algoia search</h1>
    <input type="text" id="search-input" />
    <script
        src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/autocomplete.js/0/autocomplete.jquery.min.js"></script>
    <script type="text/javascript">
        var client = algoliasearch('PACBZRD3Z1','ab4b2b226200fec5d58aa85e25b1032d')
        var index  = client.initIndex('tutor_utopian')
          $('#search-input').autocomplete({ hint: false }, [
            {
              source: $.fn.autocomplete.sources.hits(index, { hitsPerPage: 5 }),
              displayKey: 'name',
              templates: {
                suggestion: function(suggestion) {
                  return suggestion._highlightResult.name.value;
                }
              }
            }
          ]).on('autocomplete:selected', function(event, suggestion, dataset) {
            console.log(suggestion, dataset);
          });
    </script>
</body>
</html>

We will import several libraries so that autocomplete can run on our search system:

  • Import Algolia.js: Before we run the code we will import algolia.js before closing the <head> tag, because algolia.js must be run first from another script. I will import algolia.js as follows.
<head>
    <title>Duski Tutor</title>
    <script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>
</head>


  • Import Jquery: We can use jquery at least version 2, I will import it through CDN like this
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous">
</script>


  • Import Autocomplete after that we will import autocomplete.js via CDN, we place it before the closing tag of the </body>. We can import it as follows:
<script src="https://cdn.jsdelivr.net/autocomplete.js/0/autocomplete.jquery.min.js"></script>


  • Connect algolia with autocomplete.js

We have imported the library needed to create autocomplete in our algolia search system, now we have to connect our search system with autocomple.js, Autocomplete has provisions that cannot be changed, below is the code to connect our search system with autocomplete.js

Example:

<script type="text/javascript">
        var client = algoliasearch('PACBZRD3Z1','ab4b2b226200fec5d58aa85e25b1032d')
        var index  = client.initIndex('tutor_utopian')
          $('#search-input').autocomplete({ hint: false }, [
            {
              source: $.fn.autocomplete.sources.hits(index, { hitsPerPage: 5 }),
              displayKey: 'name',
              templates: {
                suggestion: function(suggestion) {
                  return suggestion._highlightResult.name.value;
                }
              }
            }
          ]).on('autocomplete:selected', function(event, suggestion, dataset) {
            console.log(suggestion, dataset);
          });
    </script>
  • Initialize: We must initialize the input element that we will use for autocomplete. the input we will use is <input type = "text" id = "search-input" />, Then to connect it we can use the id attribute of the input like this.
    Example:
    $('#search-input').autocomplete();

  • Set of results displayed: We can also set how many results we will display on the hitsPerPage key: itemsForDisplay(int).
    Example:
{
     source: $.fn.autocomplete.sources.hits(index, { hitsPerPage: 5 }),
}


  • Set Display key: We can set what key we will look for in our data in algolia, we have set the data we use in our search system in the previous tutorial. We can set it on the key displayKey:. in this tutorial, we will look for keywords by name.
    Example:
 {
    displayKey: 'name',     
}


  • Set suggestion: Now we will set the suggestion that will be displayed if the keyword is entered, The key is templates:{} in the key in object is suggestion:
    Example:
templates: {
     suggestion: function(suggestion) {
                  return suggestion._highlightResult.name.value;
    }
}

We can display what data we return to display return suggestion._highlightResult.name.value; , nameis the key that we will display according to the displayKey we are looking for.

  • Function callback in 'autocomplete:selected'

Autocomplete.js also provides a callback function to run something after we have selected the data, in the callback function there are several parameters we can use, namely event, suggestion, dataset.

Example:

 $('#search-input').autocomplete({ hint: false }, [
        {
          ......,
              ......
        }
    ]).on('autocomplete:selected', function(event, suggestion, dataset) {
        console.log(suggestion, dataset);
    });

I have done console.log () so we will see the results as shown below:

ezgif.com-video-to-gif.gif

  • Set CSS for autocomplete.js

We can add a little CSS to enhance the look of our search input, you can use and combine it with other CSS frameworks if you want, in this tutorial I will use CSS provided by autocomplete and add a little modification.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Duski Tutor</title>
    <script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <style type="text/css">
.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: #B2D7FF;
}
.algolia-autocomplete .aa-dropdown-menu .aa-suggestion em {
  font-weight: bold;
  font-style: normal;
}
</style>
</head>
<body>
    <div class="container">
      <div class="row">
        <div class="col-sm-6 col-sm-offset-3">
            <div class="page-header">
                <h1>Duski Tutor Algolia <small>Algolia autocomplete</small></h1>
            </div>
          <form action="#" class="form">
            <input class="form-control" id="search-input" name="contacts" type="text" placeholder='Search by name' />
          </form>
        </div>
      </div>
    </div>
    <script
        src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous">
    </script>
    <script src="https://cdn.jsdelivr.net/autocomplete.js/0/autocomplete.jquery.min.js"></script>
    <script type="text/javascript">
        var client = algoliasearch('PACBZRD3Z1','ab4b2b226200fec5d58aa85e25b1032d')
        var index  = client.initIndex('tutor_utopian')
          $('#search-input').autocomplete({ hint: false }, [
            {
              source: $.fn.autocomplete.sources.hits(index, { hitsPerPage: 5 }),
              displayKey: 'name',
              templates: {
                suggestion: function(suggestion) {
                  return suggestion._highlightResult.name.value;
                }
              }
            }
          ]).on('autocomplete:selected', function(event, suggestion, dataset) {
            console.log(suggestion, dataset);
          });
    </script>
</body>
</html>
</style>

We can see the results by running index.html in your browser, if there is no error then you will see results like the following picture:

ezgif.com-video-to-gif (1).gif

We have finished the tutorial about autocomplete we have learned to implement it in our search system, we have connected algolia with autocomplete.js, with autocomplete .js we can improve the User Experience for the better. I hope you can develop it even better. I hope this tutorial can help you.

Curriculum

Search system with Algolia#1 Set up algolia, Upload data, Display Search

Proof of Work Done

https://github.com/milleaduski/searchSytemAlgolia

Sort:  

Thank you for your contribution.

  • The level of difficulty should be basic.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Congratulations @duski.harahap! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes received

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Hey @duski.harahap
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.27
TRX 0.12
JST 0.031
BTC 57654.82
ETH 2888.30
USDT 1.00
SBD 3.60