Instant Search Bar in JavaScript - HTML, CSS & JavaScript Tutorial (Project)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys hey going in today's video I'm gonna be showing you how to create an instant search bar using HTML CSS and JavaScript okay so this solution is going to be done through vanilla jeaious which means there's going to be no need for any sort of external library sorry any external framework it's going to be pure jeaious and it's also gonna work on desktop and mobile devices it's gonna be responsive and it's also going to be highly customizable and easy to use from the developers perspective which means you can easily go inside here and make changes to extend the functionality of the instant search bar so let's take a look at the finished product right here in this tab as we can see we've got this instant search bar to search for users against a database so for example if I was to type in dum it's going to show me a list of users with the name dum and these are also going to be links which means I can go inside here and actually click on one of their users and it's gonna take me to the external page so unfortunately I've got this issue with my screen recorder and that is why the links aren't working it appears that if i zoom out zoom back in try again and they do work so I might just keep trying here until it does work but trust me and I have tested this and it only happens when I'm recording the screen so there we go just worked just then so just keep that in mind it does work or it should work for you but that is the final product okay and we've also got here as you just saw and we've got this sort of loading bar indicator on the top there of the search bar that's also easily done using CSS okay so let's take a look here at this tab right here so we're gonna be starting from scratch inside here okay and I'm gonna be showing you here first up just the file structure of what I currently have so as we can see right here I've got this index.html file inside that directory there and it's got nothing inside of it okay and I've also got this search dot PHP and this endpoint right here is gonna be what's doing this searching okay so I'm not going to be going into how to actually perform the search because every person watching this is going to be using their own or a different server-side technology you know some people might be using nodejs or Python or whatever so the PHP isn't too relevant but basically it just performs an SQL Curie on the on the query string that we pass in and it returns a list of results now I am gonna show you the hardy SQL window here that I've got open so as we can see that is what the table looks like we've got a first name last name and occupation okay so it's going to a search against that table there and the result of that search is going to look something like this so I'll just duplicate this tab here and then go to search PHP with a cube in the query string equal to Dom press ENTER and we get this JSON response so as we can see the JSON response looks like this now your own search script does not need to return the data in this format okay so just keep that in mind because it is highly customizable essentially inside here we've got a few properties and of course an array sorry an array of results okay so that is the bed is the search endpoint response format okay so anyway now let's begin on the HTML for the instant search bar okay so inside the index.html file the first thing to do is to make a new directory here for the instant search so we can call this directory instant - search okay and then inside here we can make a directory for CSS and a directory for JavaScript so jeaious okay now we're also gonna be heading to the material icons website because I want to be able to show a little magnifying glass here in the search bar so we can be so we can use this icon library right here so it's Google material icons they're free to use and I believe open source and you can you can include this library on your page by going to this URL and I'll leave all these stuff in the description below but basically go down here click the icon fonts for web and then copy and paste this link right here into the HTML head of your page just like that and now you can use the Google material icons okay so now let's move on to the actual HTML of the instant search bar itself okay so the very first thing to do here is to create a div which is going to be the main container for the search bar okay so we can make this div and give it a class of instance - search okay and then inside here it's going to be holding two things the first one is going to be a container for the input so basically it's going to contain the input and also the magnifying glass icon so we can call this div and instant - search underscore underscore input - container so as usual I'm using the block element modifier CSS class naming convention but you can of course name these classes whatever you like okay now I did forget to add an ID to the main div so we can say ID and we can just say search users okay cool now inside the input container we're going to be putting two things the actual input field and then the icon so for the input field we can say input okay with a type of text and also a class and this class is going to be instant - search underscore underscore input okay it's also going to have a few more properties here or attributes sorry first one is going to be spell check equal to false and that's gonna remove the default spell checking in the browser when typing in that box and also a placeholder and the placeholder text is going to be something like search users okay and that is the search bar if I save this and refresh this page we can see we get something like this okay let's add in the icon and the way we're going to be using Google material icons here is by making a new I tag with a class of material - icons and also a class of instance search underscore underscore icon okay and inside here we can just say search as the text and that right there is going to show you the little magnifying glass as the icon let's save this and refresh and we get this right here and essentially if you don't know how I did that on this icons page right here if I scroll down there's a bunch of icons here if I do a search for search we can see right there we get this search icon and basically that is how you choose and use the search icon okay so anyway let's go back inside here and move on so now we're going to be adding the HTML for the list of search results so the container div for each search result is going to be called instant - search underscore underscore results container okay and then inside here we're going to be putting a couple of results okay so we can say div with a class of instant - search underscore underscore results and inside the results and this is actually gonna be an anchor tag because of course they're gonna be links okay so we can make that an A right there and also give this an href of just for now a hash okay cool then inside here we're going to be placing both the title so basically just the person's name and also a paragraph to describe their occupation so we can say right here div with a class of instant - search underscore underscore title and inside here we can just say for example first name okay and for the let's just do first and last name okay we can also say down here a paragraph tag with a class of instant - search underscore underscore our paragraph okay inside here we can just put some lorem ipsum or some dummy text okay cool and that is basically the eight female structure for our instant search bar so I do want to point out early on that everything basically right here the results container all of this stuff is going to be generated dynamically through the JavaScript however we are going to be you know putting the HTML markup inside here just for now so we can actually style it using CSS so I'm gonna make a copy of that search result right there so we have two results to work with so now saving this and refreshing and gives us something like this okay so now we are ready to move on to the CSS for the instant search bar so inside the CSS directory let's make a new file called instant - search dot CSS okay we can of course then and just include that CSS file just up here so link for CSS at instant search CSS instant search dot CSS okay and inside the CSS file the very first thing to do here is gonna be to target the main instant search container so basically this one right here so we're gonna be targeting the instant - search class and firstly we're going to be adding a position of relative and a maximum width of 250 PX so the reason for this for this position relative is to allow us to place the loading indicator absolutely at the top of the instant search bar but we're going to get into that a bit later on and the maximum width here is so that we have a maximum width that means it's gonna try to be 250px if I can't it's gonna shrink down which makes it responsive okay now the second thing here is to set the font family of the whole search bar so we can say instant search and everything inside the instant search actually my mistake we're gonna be targeting at the instant search and also the instant search input viewer okay and we can say fun family let's make this sound serif just for now but of course you can change this to be whatever font you like okay we're also going to be targeting here instant search and also everything inside instant search so we can just put an asterisk right there and for this one we're gonna be saying transition and then background at 0.15 seconds and also a box shadow at 0.15 seconds and the reason why I'm applying this to every element inside is because many of the elements are gonna have these two these two transitions so it's easier to apply it like this and I don't see any performance issues with doing it to everything okay and when they are gonna just move on to styling up the input container so I might just save this and refresh the page to see what we currently have and we have this right here as we can see we've got the maximum width that is kicking in okay um so now let's go back inside here and work on the input container so we can say here instant search and also instant search input container okay and for both the main container and the input container we're going to be saying a water radius of 5px okay and the reason why I've set it here sorry the reason why I've set it against the input container and also the main container that is because if we were to just do something like this for example to the main container and then use overflow:hidden we're not going to be able to see the search results so that is why it's important to set it against both the input and the main container okay so moving on to a rule set for just the input container for this one we're going to start off and say display as inline flex and the reason for the Flex box here is that way we can have the input on the left side and the icon on the right side because remember this input container is gonna contain both the icon and the input field itself okay we can also say box sizing and border box to include the heading in the overall width of the actual container we can also see here with at 100 percents okay we can also say padding and make this 6px and a background of a light gray okay and essentially with this background of light gray the reason why we're putting it on the input container I can just show you real quickly if i refresh the page we get this right here so we're going to be making the background of the input field itself so this one right here we're going to be making this transparent that way the input container gets the actual decision on the background okay so now we can just go into sorry-sorry inside here now and we can target the input container once again and we can say focus within so basically we're saying whenever the actual input field gets focused we're gonna apply some styles to the input container so we're going to be saying here a background and set this to what that way if i refresh the page and then go and focus within the input container we can see the background goes to of course the white there okay and cool so we can move on here and we can actually know what I did forget to add a rule set and that is that is for that is for the instant search so let's go back up here real quickly and we're gonna say instant search I'm gonna say focus - within so we're saying essentially whenever once again the actual input field gets focus we're going to be applying these styles so we're gonna say box shadow I'm gonna say box shadow and say 0 0 3 PX and then rgba 0 0 0 and then 0.3 or 0.2 okay so now save this and refresh focus on the input field and we get the border radius sorry the box shadow applying right there along whole of the container okay let's move on now to applying some styles to the actual input field itself so for this one we can target instant search input okay and we can firstly say flex Road and set this to be one that way it takes up the remaining width of the flex flex box okay we can say border set this to be none and outline of none a width of 100% okay and some padding of zero top and bottom and 6px left and right the same value which are used up here for the input container okay we can also say backgrounds and of course make this transparent that way it goes through into the input container background okay let's save this and refresh and we have this right here okay so now here might be a good time to work on the loading indicator pop the top okay so for that we're going to be using CSS pseudo elements however we're going to be applying that only when the instance search up here gets a added class okay so we can say here instant search - - loading okay so for this one essentially the JavaScript whenever we're searching is going to be adding this class to the input field sorry the main container this dude right here so if that's the case we're going to want to show a loading indicator so let's go back inside the CSS up to the instant search section okay I'm gonna say this right here we're gonna say instant search - - loading okay and for this we're going to be using CSS pseudo elements so we're gonna say : : after just like this and if you're not too sure what these are essentially we're creating a virtual element using a CSS okay we're going to be giving a content of an empty string okay a position of absolute and this works in conjunction with a position relative up here and we can also say top back to zero zero okay I'm a left of zero a height of 2px and a background of I'm gonna be using the D code green color here so it's going to be zero zero nine five and then seven eight okay we're also gonna give this a border radius of 5px and lastly temporarily a width of 50 percent okay so now let's save this right here and refresh the page and we get something like this so as we can see of course with the loading indicator now we're gonna be applying a CSS animation to basically make it go back and forth so to achieve that let's remove this default width and then go down here and make a new keyframes okay I'm going to call this keyframes search indicator okay inside here we can just say for zero percent we can say with at 15 percent so basically at the very start of the animation it's gonna have a 15 percent whip okay we can say at halfway so 50 percent we can say with I'm gonna make this 100 percent okay and for the whole animation once it's complete its gonna be at a width back down to 15 percent okay to apply this animation we can go back up here and we can say animation and we can say search indicator at 0.5 seconds and then infinite and then ease in and then out that way with the infinite it's gonna continue happening for as long as it needs to and it's gonna take half a second to complete so now saving this and refreshing it gives us something like this okay so we can just go back inside the HTML now and then remove that class of course we can use it a bit later on so now let's go back inside the CSS and continue with the results so for the results container of course the div holding the results we can target that class so you can say instant search underscore underscore salts - container and for this one we can give it a maximum height of 250 px that way it doesn't take up too much of the vertical space on the page okay we can also say overflow of Y set to auto to produce a scrollbar a disability of hidden and an opacity of zero now these two properties here are going to be the default on when the page loads up but for now just to see what we're actually going to be doing we're going to make these two properties essentially just canceled out or commented out of course just for now okay we can also say transition set this to be visibility at zero point if I can spell this correctly so visibility at 0.1 seconds and also opacity at 0.1 seconds that way when the results container toggles between showing and hiding it's gonna have a nice fade in and fade out okay speaking of that let's make a new class or modifier class for the actual showing or hiding of the results container so we can just target the results container element just like this then we can say - - and then visible so for this class when it's visible we can say visibility set it to visible and also an opacity and set it back to one so we can see how these are are these two properties here or these two sets of properties are going to sort of switch between two hard and show the results container okay I'm so now let's just save this and refresh the page and we get something like this okay so now I'm gonna go back inside here and we can move on to doing each individual result so of course this anchor tag right here okay so let's just copy this class make it a bit easier go down here and for the search result we're gonna be saying firstly display as a block that way we can convert it from the from the default inline display on the anchor tags okay we can say color and set this they just they just a dark green a text-decoration of none to remove the default underlined which appears on the actual on the anchor tags themselves okay a padding of 10px a font size of 0.8 am so a bit smaller than the current font size and also a person of pointer to of course indicate that it is actually a link so now saving this and refreshing it gives us something like this okay let's move on to adding a hover States for the instant search results so we can just say : hover and for this one we can just say background and set this to be a very light gray okay we can also say right here instant search result and we're going to be targeting essentially every result that is not the last result so we're gonna say knots and then last of type okay and for this we're gonna say border bottom and set this to be 1px and then solid and then that light gray used up here so now saving this and refreshing we can see first off we've got that are underlined or that border between the two results okay we've also got here a hover States and we can see that the transition is working which we added at their very start okay so a few more properties left here or a few more rule sets left here for the CSS we can target the instant search title class and for this we're just going to say simply font size set to one point one am and also a font weight of bold okay and let's make a copy of this go down and just say paragraph for the paragraph we're gonna be saying a line height of 1.5 and also a margin when the margins gonna be something like a px top and bottom and 0 for left and right of course this is totally up to you on how you want your text to be displayed let's save this and refresh and we get something like this okay so if you happy with the way this looks we are basically done with the CSS however just remember to go back inside here and uncomment out these two lines let's save this now and refresh once again and we can see of course by default the results are hidden if I was to go inside the inspector here go to the results results container okay and just add the visible modifier class just like this press enter we can see they now get displayed so that is basically what the JavaScript is going to be doing so now we are ready for the JavaScript for the instant search bar okay so for the JavaScript of the instant search bar we're going to firstly just go inside the J's directory here and make a new file so any file for instant search okay and this right here is gonna be in Pascal case as we can see I've used an uppercase I and an uppercase s and that is because this right here is gonna be a class okay so we're gonna be using es6 import-export syntax okay so if you're not too sure what that is don't worry and it's actually quite straightforward more than you may think okay but anyway let's leave this for now and make a new file inside here now called instant - search dot - jeaious okay so this one's slightly different but this one is gonna be basically your main file where your instant search are gonna be sort of initialized and created and sort of configured okay so essentially this file here is going to be including the instant search class which we'll be creating it very shortly and then of course just creating those instances inside here to configure them okay so let's go inside the index.html and down below the body or just before the end of the body we can add a new script tag and this script source is gonna be for that second file we just created so it's going to be going to instant search and then and then instant - search is it's also very important we add a type here so we're gonna say tight and set this to be module okay just like that so now essentially we are ready to go for the java spirit okay so firstly I want to go inside the instant search file okay and I want to get a reference to how I did right here okay so we can just say right here Const search users is equal to document query selector and pass through here the ID of search users just like that so now of course search users refers to this one right here okay so now let's go inside the instant search jeaious class and the first thing to do here is to of course define that class so we can say class and then instant search just like that okay and then down here we're going to be saying export defaults and then instant search and basically this is just saying that one will be able to export this class from this file that way this file can then import what we exported okay so up here we can say import then say instant search from and then we can just say right here instant search in George is so now if I hover over this keyword here we can see we get instant search and we also get here class instant search meaning everything's worked okay okay so now down here like I said earlier we're going to be creating a new instance of the Instant Search class to make this work so let's make a new constant here called Instant Search he uses okay this will be equal to a new instance of our Instant Search class and for now I'm gonna leave that empty we're going to be coming back inside here and giving this some arguments but for now let's keep it empty let's instead head inside the instant search class and begin defining a few methods here to of course make the instance search work so the very first thing to do here is I'm gonna be essentially just adding definitions for each one of our methods ok so the first one he is gonna be the constructor and the constructor is gonna take in the instant search elements so we can put inside here instant search ok and the second argument or second parameter here is going to be the options ok so we can set options from right there and when I say options I'm referring to essentially we're gonna be able to pass through a bunch of you know options I guess or configuration settings so that includes things like the URL to search for in our case right here it's going to be search dot PHP we're also going to be passing through the actual query parameter so in our case the letter Q and we're also going to be passing through two functions okay and the first function there is gonna basically take the response data from the search and then transform it into a form which the instant search class is going to be able to work with and the second function is gonna let you define how the search results are gonna look inside the HTML so it sounds a bit complicated however trust me it is not too bad once we get started but for now let's leave the constructor empty and then go down here and define a couple more methods so we can say here add listeners and this one's gonna be responsible for adding a few event listeners to our input and things like that and we might also just go down here and add one more just for now and there's gonna be populates results ok and populate results is gonna take through an array of results just like that okay so and essentially just for now essentially so I'm getting to be quick here but the results here is an array of results and essentially that right there refers to our results from their response so search dot PHP and our array of results are right there okay so for now let's go inside here and say console.log here are your results results okay now we can just say console dot log and output for those results just for now okay um so now we have the options set up so we have the constructor we have add listeners and we have populate results before I get into the constructor I do want to create a je stock that type definition for the options parameter okay so let's go up here and basically this is going to allow us to take advantage of type hinting in vs code or whatever text editor you're using assuming it supports Draya stock we're gonna be able to see exactly which types of data is gonna be supported and the properties for the options object okay so let's go down here up here and type out here at type def I'm gonna say right here object inside curly braces to indicate this is gonna be an object and for the name of this top definition we can just say instant search options okay just like that just keep in mind that essentially if you go back inside this instant search Jas file I might just pass through here we might as well since we're inside here we'll just pass through search users as the element okay and essentially this right here these options this is what we are defining right now basically what should go inside this object okay so let's go back inside here and continue the jeaious doc so here we're gonna say as a first property we're gonna set the data type to be URL and that is the built in a URL object within JavaScript and the URL is gonna have a property name of search URL and this is gonna be the URL which we all sorry the URL which the search will be performed up okay you know what I'll just copy and paste my previous comments here let me have something like that so basically yeah the URL which the search bar will query to retrieve the results okay I might just copy and paste my existing three properties here so we're gonna have a property of string and that is going to be the query parameters q okay our two functions our response parser and our template function so I'll get into these two a bit later on but basically like I said the response passer takes the response and transforms it and the template function allows you to define the HTML for your results okay and that is all for the top definition of the instance search options which means we can go back inside the Instant Search file here and then start using the object so we can say for example search URL you know what my mistake I forgot to mention that we need to also go back inside the constructor and add some documentation for the constructor itself okay so inside here for the first parameter we're going to be saying that it's gonna be for the instant search an HTML element as the type and for the description here we can just say the container element for the instant search okay and for the options of course we can make use of that type definition we can say instant search options and the description a list of options or configurations so something straightforward like that okay and for the function description we can just say something like it initializes the instant search bar retrieves and creates elements okay so we'll get into this a bit later on but for now let's leave it the way it is and then go back inside the instant search jay is far and now we can make use of this type definition so back inside here we can say search URL as we can see vs code is picked up on the J stock and it is telling us we have the search URL parameter and the type is going to be a URL right there so now let's make a new instance of a URL why could be property expects it to be and we're gonna be putting inside here in my case I'm gonna be putting in might just look at my reference document right here so I'm gonna be putting in here projects and then instance - search and then search dot PHP so basically my endpoint for this search PHP file of course in your case it's gonna look slightly different but I'm also gonna be making use of the base parameter here and we're gonna be saying window dot location dot origin so essentially you can create this URL object however you like you might even want to do something like this where you say HTTP localhost and then you do your path to your search ok but essentially you need to make a URL instance for this to work I've also got a video on the URL object if you wish to check it out before continuing but I do want to show you real quickly here the results of this of this object so let's go inside the browser I'll copy that and paste it inside the console press ENTER and we can see right there the href property of this URL object is set to be search dot PHP okay cool um so let's go back inside here now and provide the second property and that is going to be query parameter our case it's gonna be simply queue okay and for the template function let's make this for now and empty arrow function and do the exact same thing for the results paz' okay like I said we'll get back into these two functions a bit later on but now essentially we've provided our options for the instant search and like I said at the very start of this video it's going to be highly customizable which means if you have many different endpoints for searching with different kinds of response data different endpoints different query parameters hopefully these properties right here are going to allow you to make it work in most scenarios ok just change these as you see fit okay cool so now let's head back inside the instance Sergius and work with these two parameters inside the constructor so firstly we can say this dot elements is equal to a new object so we're going to be essentially just keeping a reference to a bunch of elements which we're going to be using for the instant search bar the first one here is going to be called lane and this will refer to the instant search main element which we pass in okay the second one here is going to be called input and this one of course is going to refer to the actual input field itself so we can say instant search query selector we're going to be searching for the class of instant - search underscore underscore input okay and for the for the third one here this will be a results container and this one is gonna be dynamically generated as I mentioned earlier so we're gonna say document and dot creates element and pass through here the tag of div okay which means we can now go back inside the index.html and just comment out our results container okay just like that so now to finish off the constructor we need to actually save the option so we can say these top options is in for two options just like that okay and just below here we are also going to say if I can find it here we're gonna be adding a class to the actual results container to of course give it this class right here so we're gonna say this type elements results container dot class lists dot add I'm gonna say here instant - search underscore underscore results container okay and we can also say the V stop elements dot main dot append child and just append the results container that way essentially we have this structure right here with the results container has the child elements of the main one okay cool and also lastly we need to say this stop and listen is to of course call the add listeners function to actually get everything working okay so now saving this right here I might actually just go inside the Instant Search dais and say console.log Instant Search users just to see what our class looks like what our object looks like okay so now saving this and then refreshing the browser right here we can see this is our our object in its current form in the elements property we have the input which is actually null which means I made a mistake somewhere but the result container right here is working perfectly fine we can see inside the HTML just down here somewhere where is it no it is the instant search result container has been successfully appended to the instant search main element okay so let's go and actually fix this input for now okay now let's figure out why so of course I forgot the dots for the class name let's try again save this and refresh and now we have the input right there and it's working perfectly fine and for the options we can see we have of course our search URL perfectly fine and we have our crew parameter also cute working perfectly fine so let's move on to the main part of this video and that is going to be of course the actual instant searching itself so for the add listeners method the first thing to do is to add a listener for when the user types and characters inside the input field ok so we can say this stop elements dot input dot add event listener we're gonna listen for the input event and basically this event is going too far off whenever they start typing on the keyboard ok so we're gonna run this function inside here and they're gonna be saying essentially first up Const query is equal to this elements input dot value ok so the value property here essentially just refers to the text in the input field okay and then we go down here and we can say for example console dot log query so just for now let's save this and refresh the page and see what actually happens ok if I was to start typing inside here we can see in the console we get our characters each code that we type so the issue of this is the instant search search PHP file is gonna be queried every single time we type a character so there is no actual delay which means it's gonna get absolutely pumped so to fix that problem we're gonna add a half second delay to give the user some more time to actually finish what they're typing before firing off the request sir to achieve this let's go back inside here add a new a variable here called delay equal to nothing and just for now and then I'm sorry and then and then down here we can say delay is equal to sets tamir and pass through here this function and this function just for now is gonna say console dot log query okay and then just below here we're gonna say 500 okay so basically this code right here is going to only run after half a second has passed okay now we also need to say up here clear timeout for delay because of course delay right here when we assign this to be set timeout these stores are reference to the actual timeout itself so when we say clear tamiya on each input we are cancelling out the previous attempted search which gives us the delay so now saving this and refreshing we should now only see coke disappearing when our weights about half a second if I type in done really quickly we can see it only works after a half second which means the search is gonna work a lot more smoothly okay beautiful so now let's go back inside here and finish off this function properly so essentially inside the set timeout we're gonna firstly say if the query link is less than three characters long so basically if we typed in one or two characters so a minimum of three we're gonna say right here this dot populate results and pass through an empty array of results and that way of course the actual search results is going to show nothing if you type in less than three characters okay we're gonna also say return nothing then down here if we did actually have a nice longer query to actually perform the search for then we can say in this dot perform search okay perform search and pass through here query so obviously we are we are yet to create this perform search method we're gonna do that right now but basically it's gonna return us a response sorry a promise containing our results okay so we're gonna say dot then and inside here we're gonna have access to our results okay once we have our once we have our list or array of results we're going to say this dot populate results once again but this time actually populate with some real results just like that okay now I do want to just remove this line just to save this and refresh and test out the initial less than three characters thing so let's get inside here typing do and we see right there here your results with an empty array so now let's implement the perform search method to actually perform the search so let's go down here okay and we can say perform search okay let's take in our query as our streams of course this right here is going to be the characters which the user types in now I did forget to add documentation to these methods so I might just copy and paste them J stock our previously wrote so for the add listeners we can just copy and paste this right here so add listeners for elements populate results I can just say this right here so basically makes the request actually that is for the perform search of our mistake so makes the request of the search URL and retrieves the results returns a promise array of objects okay for the populate results however this one is gonna be updating the HTML to display each result under the search bar okay cool so inside the perform search let's continue with the request so we're going to be making use of fetch API to make the request to this server so firstly we're going to be constructing the URL to actually search so obviously we are passing through here a URL object however it does not contain the actual query string part so let's go back inside here make a new constant called URL equal to a new instance of URL I'm gonna be passing through here this options dot search URL and then dot two strings so basically we are creating a copy of what we passed through here and then we're gonna be saying URL dot search parens dot sets we're gonna be setting essentially a key value pair our Q equal to our value so we're gonna be saying yeah these stock options dot creeper am okay for the value we're gonna be saying query just like that okay and then I might just get in here and say console dot log URL to string okay let's say this year refresh the page and perform a search so Dom for example we can see right here this is our constructed URL just like that he falls to go to this URL we can see it's working perfectly fine so that is our constructed URL we can now actually make the fetch request but first we need to say down here this dot set loading equal to true so essentially we want the search bar to have the loading indicator at this style of the search so let's go ahead now and actually create this method so we can say set loading it'll take through our boolean value true or false and for the documentation you can simply just say right here shows all highlighting indicator for the search bar of course right here true for the showing of the indicator and false to harder for this like I said previously making use of the instant search - - loading class so we can just copy this and paste it inside here when we say this elements main class list dots toggle and pass through here our class name and then for the second argument here for the fourth parameter we can just say be right there and now it's gonna add this class if we want to show it and hide it - of course hide the search indicator so now saving this and then refreshing typing out done we can see right there we have this search indicator working perfectly fine okay let's go back inside here now and actually perform the fetch request so we're going to be returning a the results of the fetch request so we can say returned right here then we can say we can say fetch at the URL in which we constructed for the fetch options we're going to be passing through here method and make it this get now if you are using sessions you may need to say credentials and set this to be either include or same-origin just keep that in mind for me it is not required okay and now once the once the response comes back we can just say dot then and we have the response object right inside there so the response right here of course is gonna be sorry the response body is gonna be in a JSON format which means I can say return response dot JSON okay just like that and then I can say dot then and now I've got the response data so of course our response data right here is gonna be a native a JavaScript object of what we returned from this PHP file so we're gonna say right here console dot log for response data and see what results we get let's save this and refresh the page do a search for word dumb and we get right here in the console now JavaScript objects of the results if we go inside the network tab we can see of course that request went through perfectly fine we sent through the queue as the parameter of course the value of done and it's all working perfectly fine okay all right let's move on now to doing a tiny bit of error handling for the endpoint okay so for example in my search type PHP as we can see here if I don't provide a Q parameter then essentially I get a response code of 400 okay so let's handle that scenario if it does happen to occur so we can see inside here in the event for the response we can say if the response dot status does not equal 200 then we can just say throw new error and saying something went wrong with the search so of course every person here is gonna have a different way of handling this error in my case I'm just going to go down here and I'm gonna say essentially catch and right here I'm gonna have access to the error object just like that and I'm gonna be saying console dot error and then pass through here the actual error so of course like I said in your own scenario you may instead want to actually you know show the user a message or do something like that in my case I'll keep it simple and just say console era okay I'm also gonna say here very important to say return an empty array so basically now we are going to be adding adding something else here very shortly but for now we're gonna say return empty array to basically say if there was an error return no results okay and then down here we can say dot finally okay and here we can just say once we have the results now of course our results here are they gonna be an array of result objects or an empty array throws an error okay or no results finally we're gonna say this dot set loading and reset the loading back to false - of course hide the indicator up top and we're also gonna say here return results that way our our perform search here gives us the results here in which we can then say populate results to of course make them display okay so I might just save this here and refresh the browser real quickly to see how we go on I've been done and we get this right here here are your results and we actually get undefined to be honest I'm not entirely sure while we get that let's go back inside here and check it out I guess here we go so I didn't actually return the response data so of course I've actually loaded it out here but there is nothing to return so let's go down here you know and actually return each one of our result objects okay so to do this we're going to be making use of the response parser which we supplied inside the constructor here so once again the reason for this response parser is because every endpoint might be different of course in this case here for our search dot PHP it returns us in this format which means we can just say once we have this response data we can make use of the results property to of course give us the array of results okay so that being said let's go back inside here and in the response parser this right here is gonna accept a response data parameter okay then here we can just say return response data dot results okay because what I got once again the person writing this knows that this search PHP gives us this this particular format which means we can say return response data dot results just like that okay now you may also want to you know do a bit of transformation here if you wish to to make it work fine for you but basically all the instant search class needs is an array of response objects or results objects okay so now with this defined here we can go back inside here now and we can say inside the response data section we can say return this dot options dot response parser and pass through here our response data just like that so now it's gonna run their function it's gonna get the results and of course now it's going to pass it down the down the pipe here back up to our popularity here let's save this and refresh and we can type out dumb and now we get here your results we get an empty array let's let's figure out why let's try again so response data is not a function what do I do wrong here response passer result posit okay so this needs to be a response parse out my mistake as I apologize let's go back inside here and checking this out so yeah response pass that has deep property let's try again and refresh type in dumb and now we get here here your results the array of results okay let's purposely test the error handling by simply just throwing this error right here every time we should now hop down here and return an empty array let's try this out dumb throws the error and we get here our empty array so it's working perfectly fun let's remove that line right there so that is all for the fetch request and probably the most important part of this video okay let's move on now to finishing off the populate results function now I do want to do one more thing before we continue and that is to basically say whenever we focus on the input field want to be able to show the results container when we lose focus want to be able to hide the results container so let's go inside here inside the add listeners and we're gonna be saying we can say this elements input dot add event listener we're gonna listen for the focus event so basically when the user clicks on to the input field we're going to run this function inside here and we can simply just say this dot elements dot results container we can say class list adds and we can add the class of instant search results in Tayna - - visible just like that okay and do the exact same thing for the blur event so blur fires off whenever the user loses focus on the input field or clicks away so i'm blur we can remove that visible class okay so now let's go in the index.html and just uncomment our two lines here to actually see something tangible okay let's save this and refresh the page and then gain focus on the input field and we get right there the results container appearing perfectly fine so that is what that code just did now it might be a good time to just remove our HTML for the results container seeing that the last thing to do is to actually generate our results okay so let's get rid of that and now head back inside the JavaScript okay and then scroll down to the populate results method so here let's implement this method okay so firstly it's going to be removing all of the existing results if there were to be any so we can say right here right clear all existing results okay and this will be while this type elements type of results container dot first child so basically while there is a is a results in the results container we can say this dot elements dot results contain a type of remove child we're gonna be removing the first child so you can say elements results container code first child right there and then of course together clear the HTML okay we can also say here now we can actually populate each one of our results so we can say update list of results under the search bar here and now we can say for Const results of the results in which we pass in for each result we can say this dot elements dot results container dot append child we're gonna the appending a new element which we're going to be creating through the JavaScript and this is going to be a call to this dot creates results elements passing through here our result so now let's implement this method right here to actually create an instance of an element to represent one of our results this anchor tag right there okay so let's go inside here and create this result element method so we can say right here creates a result element this will take through a results object okay and I'll copy and paste my documentation for this particular method we can say here creates the HTML to represent a single result in a list of results okay so here we can make a new element we can say const anchor element is equal to a document dot create element and pass through here an anchor tag or an a tag okay we can also say here anchor elements dot class list dot add we can add the the instant - search underscore underscore results class and also we can say anchor elements and dots are insert adjacent HTML and basically this allows you to insert an HTML string inside the actual element so we can say here position as after begin that way it gets inserted inside the actual element itself okay and we can say here for the HTML string we're gonna be saying that lease options dot template function and passing through the results okay so this template function call of course refers to this one right here so let's go ahead now and pass through our results of course what here result refers to first name last name occupation etc and here we can return the HTML as the string to represent a results okay so let's use es6 template strings here by using the actual backtick character right there and we can say here multi-line string of HTML so we can say div with a class of instant - search underscore underscore title inside here pass through the first and last name of the user so we can say dollar sign and curly braces results dot first name then a space and then just say results dot last name okay we can also say it down here a new paragraph tag to their class of instant - search underscore underscore paragraph inside here we can put the person's occupation results dot occupation okay cool so now we've got this HTML being returned from this template function once again the reason why it's here is because there weren't this search bar to be generic and customizable no matter what the end point is it is about okay cool let's go back inside here now inside the create result element method and finish it off so we can say here we need to add the actual ATF attribute for the link to go through a new page so we can say yeah if provided as they link for the results so you can just say if href in results so basically if you provide the href in your result right here then let's go back then we can just say elements dot set attribute sorry anchor element anchor element that set attribute I'm gonna set the href attribute for the value of results dot a trip okay and then lastly we can return the HTML elements okay now I just forget to add some documentation here so I can just say app returns and pass through here HTML anchor Palin okay beautiful amp so now we are basically done with the instant search bar our belief so let's just save this and refresh the page and see if it actually works so let's type out dumb right here and it is not working let's figure out why let's go back inside here here we go so anchor elements how's my constant name let's try it again refresh and type out done let me get right there our list of instant search result and also we can see on the bottom right of the page just down here our links are working fine let's attempt to click on it and we go to the destination of the actual href okay so that is it's for instant search bar using HTML CSS and JavaScript thanks for watching guys and I'll see you later
Info
Channel: dcode
Views: 42,479
Rating: undefined out of 5
Keywords: code, coding, programming, tutorial, introduction, beginner, walkthrough, guide, software, development, simple, easy, english, with, example, examples, developer, lecture, recording, how, to, web, website, app, application, html, html5, css, css3, javascript, js, es6, ecmascript2015, project, projects, search, searching, bar, instant, ajax, async, fetch, api, get, post, query, database, sql, import, export, syntax, module, class, dom, document, object, model, vanilla, pure
Id: M3PbUwgEecU
Channel Id: undefined
Length: 66min 58sec (4018 seconds)
Published: Fri Mar 20 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.