A “suggest-as-you-type” search widget in 57 lines of JavaScript code.

A “suggest-as-you-type” search widget in 57 lines of JavaScript code.

<strong>A how-to for an effective search widget that shows suggestions as you type, in plain JavaScript, and using the Fetch API to GET content.</strong>

A how-to for an effective search widget that shows suggestions as you type, in plain JavaScript, and using the Fetch API to GET content.

While working on Influen$e, I wanted to make the search function a robust tool for people searching for an influencer’s Instagram.

Because discovery is a critical distinguishing feature of Influen$e, I also wanted to build in a simple recommendation function that targeted customers based on the relevance of influencers’ content to their core brand values.

In this article, I’ll share the code and walk you through how the function works.

If you know what you’re doing, you can jump to the code on GitHub.

The HTML

I’m using UI Kit 3 for my CSS framework, so this part is easy. Here’s the code:

<form id="SearchMemberForm">
    <div class="uk-margin-small">
        <div class="uk-inline uk-width-1-1">
            <button id="MemberSubmit" type="submit"
              class="uk-form-icon uk-form-icon-flip"
              uk-icon="icon: search"></button>
            <input id="MemberInput" type="search" name="ig_handle"
              class="member-search-input uk-input uk-form-large"
              placeholder="e.g., cristiano" autocapitalize="none"
              autocorrect="off" autocomplete="off" />
            <div id="PresetMember" class="uk-width-1-1 uk-margin-remove"
              uk-dropdown="mode: click; pos: bottom-justify;
              boundary: .member-search-input"></div>
        </div>
    </div>
</form>

Getting the data with Fetch API

The first thing we need to do is get an Array of objects to populate suggestions, right? So, we’ll make a request to an API or cloud function or whatever.

I’m using Fetch because all I need is a JSON object, but if you want more granular control you can use XHR just the same.

fetch('://<server>/api/', {
      method: "GET",
      cache: "no-cache",
      credentials: "same-origin",
      headers = {
          "Accept": "application/json",
          "Content-Type": "application/json; charset=utf-8",
          'X-Requested-With': 'XMLHttpRequest'
      };
  })
  .then(res => res.json())
  .then(json => {
      console.log(`JSON response ${json}`)
  })
.catch(error => console.log(error));

Fetch is pretty straightforward:

  • I send a GET request to my API endpoint at ://<server>/api/.
  • .then(res => res.json()) renders the response as JSON.
  • .then(json => {}) is where we can use that JSON.
  • .catch(error =>...); catches any errors in our request.
One thing to bear in mind, Fetch doesn’t do any error checking, it only returns a fail if something went wrong with the actual request to the server, like a 404 or 500. So, you’ll need to write your own error catching code.

If you run that code, you’ll get an array of objects. In my case it’s an Array of social media influencer objects:

Coding the UI

Now we need to turn that Array into a nice drop down list. There are two types of lists I’m going to generate.

  • One will be for automated recommendations when the user clicks the search field.
  • The other will be our suggest-as-you-type list.

To do that, we’ll pass our Array to a new function, called loadLists(). Let’s update our Fetch response to call loadLists(json):

fetch(endpoint, {
    method: "GET",
    cache: "no-cache",
    credentials: "same-origin",
    headers: headers,
})
.then(response => response.json())
.then(json => loadLists(json))  // <-- Call loadLists() here
.catch(error => console.log(error));

This passes our Array of member objects to a new function called loadLists() which looks like this:

let loadLists = (json) => {
    let members = [...json.members];

let searchSuggest = ['input', function(e) {
        filterList(event.target.value, members);
    }, false];

formInput.addEventListener(...searchSuggest);
presetMembers.innerHTML = userList(members.slice(0, 3));

}

There’s a couple of things going on here.

  • First, we’re using a spread operator [...json.members] to get to the objects in our array.
  • Next, we’re creating an Array called searchSuggest, and within calling the filterList() function.
  • Then, we add an event listener to the input field in our HTML form.
  • And finally, we’re loading the top three recommended influencers into the presetMembers drop down menu (I’ll get to that soon).

The reason we created the searchSuggest Array is because we want to pass the event and the function call to our event listener. It’s just a cleaner way of separating our functions.

Okay, let’s have a look at the filterList(); function.

let filterList = (key, members) => {
    let listEl = document.getElementById('MemberList');
    listEl.innerHTML = '';  // <-- Clear the field to avoid repeated entries.

for (let i = 0; i &lt; members.length; i++) {
    if ((members[i].ig_handle.toLowerCase())
        .indexOf(key.toLowerCase()) &gt; -1) {
        let node = () =&gt; (
            `&lt;li class="member-link"&gt;
                ${members[i].ig_handle}
            &lt;/li&gt;`
        );
        if (listEl.childNodes.length &lt; 5) {
            listEl.insertAdjacentHTML('beforeend', node());
        }
    }
    if (key.length &lt; 2) {
        listEl.innerHTML = '';
        presetMembers.innerHTML = userList(members.slice(0, 3));
    }
}

};

Wow, that’s the biggest chunk of code so far. Let’s walk through it.

First, we have a couple of arguments key and members.

So, the argument members is obviously our Array of members we got from our Fetch API call.

But what is key?

Remember when we created that Array called searchSuggest? Reminder, the event we added is

searchSuggest = ['input', function(e) {...

We’re adding an event listener for input, basically saying for every character the user types into our form field, trigger the input event. Get it? The input event is a keystroke, which is our key argument.

In other words, every time a user types a character into our search field, fire the filterList() function.

Next, we’re getting the MemberList element from our HTML. This is where we’ll generate our member list.

Let’s take a look at our for loop.

In this line we’re converting all text to lowercase so our searches will be case insensitive:

if ((members[i].ig_handle.toLowerCase()).indexOf(key.toLowerCase()) > -1)

Then for each character entered, we iterate through our members list and create a new list item node:

let node = () => (
    &lt;li class="member-link"&gt;         ${members[i].ig_handle}     &lt;/li&gt;
);

${members[i].ig_handle} is how we’re identifying our members. In my case I’m looking them up by their Instagram username ig_handle.

Then we get up to five members and add them to our list using insertAdjacentHTML:

if (listEl.childNodes.length < 5) {
    listEl.insertAdjacentHTML('beforeend', node());
}

And finally, if the user enters less than two characters — or backspaces to less than two characters — reload our presetMembers, hiding our suggestions:

if (key.length < 2) {
    listEl.innerHTML = '';
    presetMembers.innerHTML = userList(members.slice(0, 3));
}

Stitching it all together

Let get our elements using getElementById:

let formInput = document.getElementById('MemberInput')  // <-- form <input> field
let presetMembers = document.getElementById('PresetMember'); // <-- div for our list

Then we’re going to use template literals to generate our <ul> markup that we’re inserting into the presetmemberdiv.

let userListItem = (item) => (
    &lt;li class="uk-width-1-1"&gt;         &lt;img class="uk-border-circle uk-width-1-4 uk-float-left" src="${item.profile_pic}" data-uk-image /&gt;         &lt;p class="uk-width-3-4 uk-text-lead uk-text-truncate uk-padding-small uk-padding-remove-vertical"&gt;${item.ig_handle}&lt;/p&gt;     &lt;/li&gt;
);

let userList = (list) => ( &lt;ul id="MemberList" class="uk-list uk-list-divider uk-padding-remove-vertical"&gt; ${list.map(userListItem).join('')} &lt;/ul&gt; );

There it is. Save the file and (hopefully) it should all work beautifully!

I hope this was helpful for you. Feel free to comment with questions, revelations, insults, etc.

Originally published by Michael Lisboa at https://medium.com

Learn More

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ The Full JavaScript & ES6 Tutorial - (including ES7 & React)

☞ JavaScript - Step By Step Guide For Beginners

☞ The Web Developer Bootcamp

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js

☞ Visual Studio Code Settings and Extensions for Faster JavaScript Development

☞ Vue.js Authentication System with Node.js Backend

javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Create a Line Through Effect with JavaScript

In this post we are going to create an amazing line through effect, with help of CSS and lots of JavaScript. So, head over to your terminal and create a folder LineThroughEffect. Create three files -index.html, main.js and styles.css inside it.

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.