How to create a Simple Autocomplete Library with Vanilla JS

Published on: May 1, 2021

Welcome to the 60th Easy JavaScript tutorial. Today we create our own library. What is a library?

The most basic explanation is that a library is reusable code. It's a collection of resources that does not change and can be used by other resources without much hassle. 

This tutorial is a long one and will mostly be in video format. This tutorial combines a bunch of other topics that I've covered in the past. We'll combine all of those topics into today's video and you will learn how to create an autocomplete library in vanilla JavaScript. 

Note: The library that we are creating shouldn't be used in production. I'm using HTML Datalists for this and it's ugly. It might be good for small projects but plenty of other libraries exist that you can import and use in your project. 

The main point of this video is to not talk about one specific library. I want to show you how you can create any kind of library so that you can reuse your code over and over to create new tools and application. 

You'll need to know the four following topics for this tutorial:

  1. JavaScript Modules
  2. Crawl JSON using Recursive Functions
  3. Array methods
  4. Array.forEach() Loops

This library will allow you to implement an autocomplete function in your code with a few simple lines. In our HTML, we'll have our datalist as shown:

        <datalist id="autocomplete-list">
        </datalist>

And in our JavaScript, we can target that id and call our Autocomplete function (ac):

        ac.autocomplete(data, el, "car")

Substitute el with whichever element you used for your datalist.

To learn how to create the Autocomplete library, check out the video or just take a look at the code at the following link on GitHub: https://github.com/naztronaut/sal/blob/master/autocomplete.js

You may notice that there are less than 40 lines of code in that file and that's the beauty of this. You can create very simple libraries that can send up saving you a TON of time. Do you have things you do to text over and over again? Create a library!

I know this written tutorial isn't very intensive. I broke down the videos into chapters so I hope that helps you get oriented. If you have questions, ask away! Have you created your own library from scratch? Let me know, I'd love to see it!

Patreon

I do these projects to learn and teaching is a good way to learn. But if you do want to support me, head on over to Patreon and become a Patron: https://www.patreon.com/nazmus

If you've implemented this project, I'd like to see it! So please share it with me through any of my regular channels. 

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!

Resources:

Find the code on GitHub at https://github.com/naztronaut/sal



Comments: