Project 6:Ajax Type Ahead
Tags: javascript, webdev, html, css
Published: 2021-12-06 18:56:45

Welcome to my "Build 30 Js Projects in 30 Days" Series .This is day 6 and project 6. If you haven't read the other articles in this series please check them out first. I'll list them at the end of this article.

As mentioned in my previous article. This is the Day 6 challenge of [Wes Bos Javascript30 course](https://javascript30.com/).

##<u>*Final result:*</u>

This is a filter for city which is a very common feature in websites nowadays.It will display all the cities that matches the keywords entered by user. 


 {% codepen https://codepen.io/prachigarg19/pen/RwLrVdX %}

[My source code](https://github.com/prachigarg19/Javacript_beginner_projects/tree/main/js30)

As always before starting download the starter files from [here](https://github.com/wesbos/JavaScript30). I've made a separate article on how to download starter files, you can check it out [here](https://dev.to/prachigarg19/build-30-javascript-projects-in-30-daysday-0-2m8j).

## PART 1:HTML
Here I've created two divs, container will contain heading and searchbox and second div display-part will display the list according to value entered by user.

## PART 2:CSS
Now we are going to style our project.Here I've simply used flex on body to center our content. I've also added css to city-list which will contain our list i.e. to be displayed

## PART 3:JAVASCRIPT
Now we will make our project interactive.
This is the major part of this project. 
The idea is to read user's input ,display list of cities matching that input and then display the city selected by user from this list on the input box.We will also highlight the letters entered by user in the list.

We will first fetch the data from the [link](const url='https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
) . This link contains our data in json format. We will use fetch function to get data from this link. Also we will use map function [check this article to know more](https://dev.to/prachigarg19/project-4-array-cardio-day-1-3b1k) to get a new array with just city names and store it in cities variable.

```
let data=document.getElementById('text');
// fetching 
let cities;
fetch(url,{
    method:'GET',
})
.then(response=>response.json())
.then(text=>{
    cities=text.map(item=>item['city']);
    
})
```
Now we will use keyup listener. This event is triggered whenever user enters a key in the element (here textbox). We will then generate regex expression using [regExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) and store all the cities matching this expression into display. We will then call result function to display the list,highlight input by user and changing value in textbox to the value clicked by user.

```
data.addEventListener('keyup',(e)=>{
    if(e.target.value==="") return;
 display=cities.filter(item=>{
     regex=new RegExp(e.target.value,'gi');
     return item.match(regex)
  
})
result(); //to display list
})
```
<u>result()--></u>
<u>Displaying and highlighting part-</u>
We will traverse through our display array and store it in a string which will later be appending to our display-part class.
For highlighting, we will replace each item's regex equal part to span part and use inline css to style it.

```
let resultdisplay=document.getElementById('list');
 str="";
    for(let item of display)
    {   let city=item.replace(regex,`<span style="background-color:green;">${data.value}</span>`);
        str+=`<ul><button value="${item}" class="city-list">${city}</button></ul><hr>`;  
    } 

    resultdisplay.innerHTML=str;

```
 Notice that I've given a class and value to each list item which will be later used to display city selected by user.

<u>Changing text box display text</u>
Now we will select all elements with city-list class. We will traverse this list and listen for event on each item. When the user clicks any button the click event will be triggered and we will change value of textbox to the value of the button clicked. 

```
try{
    let cityarr=Array.from(document.getElementsByClassName("city-list"));
    for(cityitem of cityarr){
    cityitem.addEventListener('click',(e)=>{
        data.value=e.target.value;
        resultdisplay.innerHTML="";
        //removing list after user chose city
    });}
        }catch(TypeError){
        return;
        }
```
I've used try-catch block as if user clicks on the highlighted span part the textbox will give TypeError as span html part in result function didn't have a value attribute->

```
let city=item.replace(regex,`<span style="background-color:green;">${data.value}</span>
```
So we will simply catch this error and return from the loop.

##<u>*Things I learnt:*</u>

1.keyup event listener
2.How to highlight part of the list elements.
3.Better understanding of regex.

## <u>Previous article from this series:</u>

First of all thankyou for the great response on my previous article.🥰
If you haven't checked it out here is the link.:
[Project 5 day 5](https://dev.to/prachigarg19/project-5flex-gallery-55jd)

## <u>Conclusion</u>

That's it for today's project.Next project will be Array Cardio day2 .

If you have any doubts or suggestions please do let me know in the comment section. I'll be more than happy to interact with you.

If you like this series and want to be a part of it, do consider following me at @prachigarg19

Thanks for reading. :)