Using Swiftype with Typeahead.js (Part 3: Connection)
Typeahead.js is a popular autocomplete library and you can configure typeahead.js to be used with your Swiftype engine. This is the third part of a three part tutorial to configure Swiftype with typeahead.js. The first section taught you how to configure your engine with typeahead.js and the second section taught you how to customize the dropdown suggestion menu.
In order to complete this tutorial you should have:
- Completed Tutorial 1: Configuration
- Completed Tutorial 2 (Optional): Customization
- OR already have typeahead.js configured to work with your indexed Swiftype engine
This tutorial will teach you how to:
- Connect your search bar with Swiftype search using the JavaScript embed found on the installation tab
Results
Below is the finished result for this tutorial. Follow the tutorial for step-by-step instructions.
See the Pen typeahead.js, part 3 by Swiftype (@swiftype) on CodePen.
Add the JavaScript embed code
The JavaScript embed code is found on the installation tab in your Swiftype dashboard. This code allows you to have customize your search bar and still use the dashboard for all other features. Go into your dashboard and copy and paste the code directly into your file where your search bar is located.
<script type="text/javascript">
(function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
(w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
})(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');
_st('install','YOUR-INSTALL-KEY','2.0.0');
</script>
Add a keydown event handler
The current embed looks for your search bar to be an input field with a specific class (st-input
), and it applies our built-in autocomplete and search to this input. We are not going to apply the st-input
class name to our input because we already have typeahead.js working and do not need to utilize Swiftype's default autocomplete. We do need to add an keydown event handler to see when the user presses the "Enter" key for Swiftype's overlay to appear.
<script>
$('.typeahead').keydown(function(key) {
if (key.keyCode == 13) {
window.location.hash = '#stq=' + $(this).val();
}
});
</script>
Your search bar is now configured to use Swiftype's JavaScript embed and display search results with Swiftype's overlay.