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

View this thread on steempeak.com
· @duski.harahap · (edited)
$46.54
Search system with algolia part#2 Use Autocomplete.js, Connect algolia with autocomplete.js, and Display Suggestions
#### Repository
https://github.com/Algolia

#### What Will I Learn?
- Use Autocomplete.js
- Connect algolia with autocomplete.js
- Display Suggestions

#### Resources
- Algolia - https://www.algolia.com
- Algolia autocomplete - https://github.com/algolia/autocomplete.js


#### Difficulty
Intermediated

### Tutorial Content

This tutorial is a continuation tutorial from the [previous](https://steemit.com/utopian-io/@duski.harahap/search-system-with-algolia-part-1-set-up-algolia-set-up-algolia-in-javascript-data-generator-and-display-search-result) 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:**
``` html
<!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.
``` javacript
<head>
	<title>Duski Tutor</title>
	<script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>
</head>
```
<br>
- **Import Jquery**:  We can use jquery at least version 2, I will import it through CDN like this
``` javascript
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous">
</script>
```
<br>
- **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:
``` javascript 
<script src="https://cdn.jsdelivr.net/autocomplete.js/0/autocomplete.jquery.min.js"></script>
```
<br>

 - **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:**
``` javascript
<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();```
<br>
- **Set of results displayed**: We can also set how many results we will display on the ```hitsPerPage key: itemsForDisplay(int)```.
**Example:**
``` javascript
{
     source: $.fn.autocomplete.sources.hits(index, { hitsPerPage: 5 }),
}
```
<br>
- **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](https://steemit.com/utopian-io/@duski.harahap/search-system-with-algolia-part-1-set-up-algolia-set-up-algolia-in-javascript-data-generator-and-display-search-result). We can set it on the key ```displayKey:```. in this tutorial, we will look for keywords by **name**.
**Example:**
``` javascript
 {
    displayKey: 'name',	    
}
```
<br>

- **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:**
``` javascript
templates: {
	 suggestion: function(suggestion) {
		          return suggestion._highlightResult.name.value;
	}
}
```
We can display what data we return to display ```return suggestion._highlightResult.name.value;``` , ```name```is the key that we will display according to the ```displayKey``` we are looking for. 
<br>
- **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:**
``` javascript
 $('#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](https://ipfs.busy.org/ipfs/QmNsjWB2SWjEFEdHbrJ7XcTsPgnNfT1eSt41R2YL7iBXuY)

- **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:**
``` html
<!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](https://ipfs.busy.org/ipfs/QmXDAnTLvMNVYGLpFChr4fQJXs3fv7eej4xnweEbwe8wyv)

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](https://steemit.com/utopian-io/@duski.harahap/search-system-with-algolia-part-1-set-up-algolia-set-up-algolia-in-javascript-data-generator-and-display-search-result)

#### Proof of Work Done
https://github.com/milleaduski/searchSytemAlgolia
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 120 others
properties (23)
post_id58,790,988
authorduski.harahap
permlinksearch-system-with-algolia-part-2-use-autocomplete-js-connect-algolia-with-autocomplete-js-and-display-suggestions
categoryutopian-io
json_metadata{"image":["https:\/\/ipfs.busy.org\/ipfs\/QmNsjWB2SWjEFEdHbrJ7XcTsPgnNfT1eSt41R2YL7iBXuY"],"app":"busy\/2.5.4","users":["duski.harahap"],"links":["https:\/\/github.com\/Algolia","https:\/\/www.algolia.com","https:\/\/github.com\/algolia\/autocomplete.js","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/search-system-with-algolia-part-1-set-up-algolia-set-up-algolia-in-javascript-data-generator-and-display-search-result","https:\/\/github.com\/algolia\/autocomplete.js","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/search-system-with-algolia-part-1-set-up-algolia-set-up-algolia-in-javascript-data-generator-and-display-search-result","https:\/\/steemit.com\/utopian-io\/@duski.harahap\/search-system-with-algolia-part-1-set-up-algolia-set-up-algolia-in-javascript-data-generator-and-display-search-result","https:\/\/github.com\/milleaduski\/searchSytemAlgolia"],"tags":["utopian-io","tutorials","javascript","algolia","web"],"community":"busy","format":"markdown"}
created2018-08-05 11:12:30
last_update2018-08-05 11:16:06
depth0
children3
net_rshares30,020,507,857,195
last_payout2018-08-12 11:12:30
cashout_time1969-12-31 23:59:59
total_payout_value35.376 SBD
curator_payout_value11.168 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length10,082
author_reputation60,101,995,119,153
root_title"Search system with algolia part#2 Use Autocomplete.js, Connect algolia with autocomplete.js, and Display Suggestions"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (184)
@portugalcoin ·
$0.03
Thank you for your contribution.

- The level of difficulty should be basic.

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/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](https://review.utopian.io/result/8/21113313).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  ,
properties (23)
post_id58,799,081
authorportugalcoin
permlinkre-duskiharahap-search-system-with-algolia-part-2-use-autocomplete-js-connect-algolia-with-autocomplete-js-and-display-suggestions-20180805t130910372z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit\/0.1","links":["https:\/\/join.utopian.io\/guidelines","https:\/\/review.utopian.io\/result\/8\/21113313","https:\/\/support.utopian.io\/","https:\/\/discord.gg\/uTyJkNm","https:\/\/join.utopian.io\/"]}
created2018-08-05 13:09:09
last_update2018-08-05 13:09:09
depth1
children0
net_rshares18,573,764,302
last_payout2018-08-12 13:09:09
cashout_time1969-12-31 23:59:59
total_payout_value0.022 SBD
curator_payout_value0.006 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length568
author_reputation214,343,891,436,406
root_title"Search system with algolia part#2 Use Autocomplete.js, Connect algolia with autocomplete.js, and Display Suggestions"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (2)
@steemitboard ·
Congratulations @duski.harahap! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

[![](https://steemitimages.com/70x80/http://steemitboard.com/notifications/voted.png)](http://steemitboard.com/@duski.harahap) Award for the number of upvotes received

<sub>_Click on the badge to view your Board of Honor._</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>


To support your work, I also upvoted your post!


> Do you like [SteemitBoard's project](https://steemit.com/@steemitboard)? Then **[Vote for its witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1)** and **get one more award**!
properties (22)
post_id58,825,228
authorsteemitboard
permlinksteemitboard-notify-duskiharahap-20180805t185141000z
categoryutopian-io
json_metadata{"image":["https:\/\/steemitboard.com\/img\/notify.png"]}
created2018-08-05 18:51:42
last_update2018-08-05 18:51:42
depth1
children0
net_rshares0
last_payout2018-08-12 18:51:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length738
author_reputation38,705,954,145,809
root_title"Search system with algolia part#2 Use Autocomplete.js, Connect algolia with autocomplete.js, and Display Suggestions"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@utopian-io ·
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.**

<a href='https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
post_id59,163,676
authorutopian-io
permlinkre-search-system-with-algolia-part-2-use-autocomplete-js-connect-algolia-with-autocomplete-js-and-display-suggestions-20180809t041008z
categoryutopian-io
json_metadata{"app":"beem\/0.19.42"}
created2018-08-09 04:10:09
last_update2018-08-09 04:10:09
depth1
children0
net_rshares0
last_payout2018-08-16 04:10:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length305
author_reputation152,913,012,544,965
root_title"Search system with algolia part#2 Use Autocomplete.js, Connect algolia with autocomplete.js, and Display Suggestions"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000