HTMX Crash Course | Dynamic Pages Without Writing Any JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on guys in this video we're going to be looking at and experimenting with HTM X it's a small JavaScript library that allows us to create Dynamic front ends without having to write any JavaScript at all and we can do this by using special attributes in our HTML called hyperscript attributes so we can basically make HTTP requests just by adding in a specific attribute so if we look at the homepage here you can see that there's a button and there's an H post attribute so what this will do is it will make a post request to whatever this endpoint or this route is and there's also HX get put patch and delete so as it says here under motivation why should only get and post methods be available so traditionally when you create a form and you submit to a server you can only do method equals get or post but with hmx you can use put patch delete so that right there is very helpful and then you can also make HTTP requests using any element not just a tags and form tags like you can with you know regular HTML and then you have methods I'm sorry attributes like HX swap which will take the response whatever this responds with and it will swap this button for whatever that response includes so you are pretty dependent on having a backend this isn't something like Alpine JS where you want to use it just to have some some little conditionals and Loops within your HTML without writing JavaScript Alpine's great for that and you can actually use both of these together this is more for full stack applications rather than you know small front-end applications because you're always making a request to some kind of endpoint now what we're going to do is use node and Express on our back end but it could be absolutely anything and in fact HTM X is getting really popular with d Jango so that's a real popular stack it's also used a lot with goang but you could have anything as your your back end but like I said we'll be using node and express now HTM X is is really small it's only 14 kilobytes so it's very very lightweight um so if you want to have some Dynamic functionality and you know you want to easily make requests and replace certain parts of your application without having to make the page reload and you don't want to use uh you know a frontend framework like react or uh view then it's a great option so if we look under reference you'll be able to see all the different attributes that are available so HX get and post those will make get and post requests and then you also have your delete and your put in your patch um HX swap we looked at that now many times you might not want to just swap or replace the element that's making making the requests with the response but you want to Target somewhere else so that's where you would use HX Target so you specify the target element to be swapped and HX trigger is used to specify the event so if you want it on a click or a mouse over any event you can make um have it make an HTTP request all right now instead of just kind of going through and explaining all these what we're going to do is we're going to create a couple small projects where we're using HTM X uh on our front end and we'll have a simple node.js and express server on our back end so let's get into it all right guys so as I said we're going to be using nodejs and express as our back end so we're going to just spend a couple minutes setting up a very basic server we want to have a public directory where we can serve HTML files and that's where our HTM X attributes will go okay so if you if you aren't familiar with no noden Express just kind of bear with me we're just going to set this up really quick so you do have to have nodejs installed um go to nodejs.org download it install it and you should have access to the node command okay and I'm just using my integrated terminal here so the first thing I'm going to do is generate a package.json so we'll say npm innit Dy and that will create our package.json file and as far as what I want to install as dependencies we just want Express so npm install Express and then I also want to install as a Dev dependency so I'm going to use- uppercase D nodemon just so we don't have to restart the server it'll continuously watch our server file all right and then in the package.json I'm just going to add a couple things here I want to be able to use the um es module syntax the import over the commonjs require syntax so I'm just going to add here type and we're going to set that to module over commonjs and then we'll create a Dev script that will run our server file which we haven't created yet it'll run it with nodemon so let's say nodemon and then server.js okay that should be all we need to do in here now let's create our server JS file okay so this is just our the entry point to our back end and what I'm going to do is just paste in some a couple lines of code here um actually we don't need xss just yet um so basically we're just bringing an Express we're initializing it into this app variable and then we have a couple lines of middleware so this will make it so the public folder that we create is static and we can just serve HTML files from it and then these two lines here are just middleware so that we can get data from um either adjacent API clients or form bodies and then here we're just starting the server we're listening on Port 3000 so we should be able to now run npm runev since we created that script and you can see it's listening on Port 3000 we haven't created any routes yet so there's nothing to really to to to hit or go to but our server is up and running all right so now let's create a folder called public and that's where like I said all of our HT ml files will go so I'm going to say index HTML we'll just generate some HTML here for the title I'll say HTM X crash course and I'll just put an H1 in here and for now just say hello all right now since I made this public folder static I should be able to go to my local host 3000 and see that index HTML file so let's say Local Host uh not 8,000 we want 3,000 and we see hello okay now to get started using HTM X there's a couple ways to do it if we go to docs and then installing so you can download it locally if you want and include it in your file structure you can install it with npm if you're using front-end tooling or the easy way to do this which is what we're doing is the CDN so we just want to grab this script tag put that in any HTML file where we want to use it and then in addition to that I just want to use um uh Tailwind so let's add that script tag as well so that's going to be source and htps CDN do Tailwind css.com okay and then if we look at the page now the font should change if I reload so now we know Tailwind is included all right and I'm just going to make these smaller so we can see them both at the same same time now the first thing that I want to do is is basically just show you how we can have a button that will make a request and get that response and put it into the browser without writing any JavaScript just by having a couple attributes so in the body here I'm just going to add a couple classes I'm going to wrap this in text Center and then we'll just have an H1 and I'm going to add let's say text these are just Tailwind classes font Bolt and let's do my so margin on the Y AIS 5 and I'm just going to say simple request example okay and this is the code that will be in the final repo so that's why I'm kind of setting it up like this now we're going to have a button and let's just make it we'll say BG blue 500 let's do text- white and padding y will do two and then padding X we'll do three whoops didn't mean to do that and let's do My5 we'll make it rounded large and that should do it so in the button text we'll just say fetch users because that's what we're going to be fetching okay so if I save that and we reload now we have this button obviously this doesn't do anything at the moment but what I want to do before we we even interact with our with our own server I just want to you an example where we could use a public API like Json placeholder which just will allows you to fetch fake users to-dos whatever you want so on the button here I'm going to create a get request and I can do that with HX dget okay and then in here I'm going to put the URL that I want to make that request to which is going to be Jason placeholder do typy code.com users and that should give me an array of of users um now obviously you're probably not going to want to put that array directly in the body but I'm just giving you an example of making a request and doing something with it now in addition to the to the get requests we can do HX DT trigger and then specify the event when we want this to happen in this case we want it to be a click all right so what I'm going to do is come over here reload click fetch users and what happened is it made that request it got the response which is this Json array and it put it inside of the button okay because we didn't specify any Target or swap or anything like that now the trigger we don't even need this if it's if we want to click because that's the default for a button however if we wanted something different like let's say um Mouse over and then if I reload and I just just Mouse over the button it makes the request then so you're not bound to just certain events where you know to make requests and of course we're not writing any JavaScript now we like I said if it's a click we don't need the trigger so I'm going to get rid of that and we could also use HX Swap and what that'll do is it'll allow us to swap out the button for uh for the response and again this is a uh an array right adjacent array usually what you would get back from your server is markup so you would replace it with like an HTML list of users which I'm going to show you in a second uh now these swap swap can take in like outer HTML inner HTML uh as well as some other selectors but I'm going to do outer HTML now if I click the button you'll see the button goes away and the outer HTML is then replaced with whatever this responds with all right so hopefully that makes sense now I want to move on to actually having a list of users instead of uh just an array so we're not going to use this public API anymore we're going to use our own so let's replace that with with just slash users and since there's no domain name or anything then it's going to look on our own server so let's save that if I click it nothing happens but if we look in the the console here you'll see it is making a request it's just a 404 because this doesn't exist exist so let's create that so now I'm going to go to my backend to server.js and I'm just going to put all my routes in this directly in this file it's a little bit messy but if you want you can um create separate route files if you know how to do that so let's say we're going to handle let's say handle get request uh to fetch users all right so the way we do that is take our app variable and we want it to to be a get request that we're handling so.get and then slash users and what I'm going to do is just uh uh yeah we'll just we'll just do a just a static array of users for now and then I'll show you how we can still get users from Json placeholder but make it a formatted list rather than sticking an array in so we want our callback function here oops and that's going to take in Quest and response objects and for the users we'll just say users set to that set it to an array and they're just going to have a name and an email uh actually I'm sorry just a name an ID and a name so let's say ID one name and then let's just copy that down a couple times we'll say save Bob Williams change that to two three and then we'll do say Shannon Jackson all right so we have some users that I want to use in the list that we that we return from this uh from this route so we're going to take our response object here which has a method called send and then in here we'll put some back ticks because we want this to be a template string and then I'm just going to have in H1 I'm just going to give it a class of text- 2XL and let's do font D bold and we'll do margin uh yeah we'll do my4 all right and we'll just say users okay now under that is where I want to have our ul and we want to then Loop through the users and output a list item for each one so let's use our template literal syntax here take our users we're going to map through and say for each for each user then we're going to return a list item and inside that we'll have the username so let's say user.name now this will be an array because we're taking an array and we're map we're using map but to turn it to a string all we have to do is add on. jooin and just pass in an empty set of of single quotes all right so that should do it let's save that and now when I come over here and I click let's reload this click fetch users now instead of just getting an array in the browser we get a heading and we get our users in a in a list and we happen to be using node and express but you could do this with anything like I said Django is pretty popular with HTM X and our front end of course we have no JavaScript at all we just added a couple attributes now the way we have it at the moment we click the button and it replaces or it swaps with the response but you probably want to put that somewhere else rather than replacing the button and that's where target comes in or HX D Target in fact we can get rid of the Swap and now say Target and you can put certain keywords in here like I could say this to mean this particular button or this element I could do um like next sibling previous sibling but you can also put just straight IDs in classes so I'm going to say ID of users which of course then I have to create that so let's go under the button here and let's create a div with the ID of users oops okay so what should happen now is this is where the response should go so let's reload and click the button and now you you can see it's put in that div and then another thing you could do this is well I'm not going to keep this but just to show you that it exists we have HX confirm if you want to do a confirmation we'll say are you sure you want to fetch users so if you're making like a delete request or something this would be really helpful and and now you'll see if I click I get that alert or that that confirmation but I'm not going to keep that so let's get rid of that now I know this is backend stuff but I want to make it so that we instead of getting just this static array of users we get it from Jason placeholder so we'll comment out these users and since I'm going to be making a fetch request and using a sync await I'm just going to add a sync to this function and then right above the send we can just make our requests so we'll say the response is going to go in this variable we're going to await and and fetch from https Jason placeholder uh placeholder do typy code.com users okay then we just want to we'll say users set that to await and we want from that response we want the Json and then here we don't have to change anything because we have our users now coming from there we're going to Loop through and output the names so let's save that reload and click fetch users and now you'll see we get I think it's the latest 10 users from the API all right now I want to show you the HX indicator attribute which allows you to have some kind of loading or some kind of spinner graphic or whatever you want while it's waiting for the server so to do that we'll go back into our HTML file and let's add another attribute of HX D indicator and what you'll do is set this to an element that you want to show when it's interacting with the server so let's say an ID of loading and of course we need to create that so you can put that wherever you want it to display I'm going to put it right above users and it needs to be a span with the class of HTM x- indicator and then whatever the ID that you used in my case loading and I could just have like that if I wanted but I'm going to use an image a gif so in public I'm going to create an IMG folder and I'm just going to bring over the image which you can get from the final repository if you want to use it it's this loader. GI so this right here and then inside that span I'm going to have my image tag and I'm just going to add a class of M Auto and h10 which will make it smaller and then the source will be IMG SL loader GIF and we'll say loading all right so if I save that you can see it really quick but it's I mean obviously it's a quick server that it's local so what I'm going to do is just kind of mimic a slower server so here let's just use set timeout and just wait two seconds so I'm just going to wrap this code here we'll say set timeout and that takes in a function and it takes in um however long you want to wait let's say 2,000 milliseconds which is 2 seconds and in this function is where I'm going to put this okay this stuff so we'll cut that and we'll put it in here all right and then we're getting this error because since we're now using this call back we have to make this a sync now we'll reload and I'll click the button and now it's waiting 2 seconds and you can see it shows the indicator as it waits all right and again very very simple frontend code now there may be cases where you want to send data with your request and we can do that with HX vals so let's say we want to send a number for a limit that we want to set on the users maybe we want to set it to three or five so what we can do is add H x- vals and we can set this I'm actually going to use single quotes here because in this object we need to wrap this in double quotes like adjacent object so I'm going to say limit and then set that to five all right now I can get this I can I'm sorry I can get this value by using this key with request. query. limit or whatever this is so let's go back to uh back to our back end and I'll put this right in the set timeout let's say const limit and we can get it with request. query. limit I do want to make this a number so I'm just going to add a plus sign here cuz it's obviously it comes in as a string and I'm just going to say or 10 so if it doesn't ex if this doesn't exist then we'll make the default 10 and then with the Json placeholder API you can add a query string of underscore limit and set it to what you want so I'm going to change these quotes to back ticks this one too let's change that to a back tick because I'm going to do question mark after users and then underscore limit and then I'm going to set that to whatever that limit is okay which I set it to what five so now when I come back over here and reload fetch users now I get five users if I change this to let's change it to three fetch users and now I get three because I'm sending this data to the back end through a simple attribute all right so I think that's all I want to do with this particular project so I do want to save this HTML so I'm going to just copy it and I'm going to create another folder in public and we'll call this request. HTML and this will all be in the the repo in the description but I'm going to paste that in and save it and now we can try something else so let's see I'll just get rid of everything in the body all right now what I'm going to do next is just create a very simple temperature um converter where we can pass in a Fahrenheit temperature and it gives us Celsius back so basically we want a form um event so when we submit the form it will go to the back end it'll do the calculation to get the temperature and then it'll send back some markup that will show us you know whatever is Fahrenheit equals whatever Celsius so I'm just going to paste in the HTML the body here um there's no HTM X it's just the the interface which is very simple so I just added a gray body we have a container we have a card and an H1 and then a form with a single input which is um Fahrenheit has the name of Fahrenheit all right so to make the request we're going to want to add onto the form this time not not a button so let's say HX d trigger and we'll set that to submit which is actually the default so we don't we don't really need to add the trigger here but I'm just going to add it anyway now I want this to actually be a post request so instead of HX get I'm going to do H HX post and let's say slash convert which will be the route that we want to hit on our back end and then where I want to put the response in the body let's say Target h h HX Target and I'll set that to an ID of result okay so that's where we're going to put it and then let's also do an indicator so HX indicator and I'll set that to an ID of loading again all right and then of course we need to have both of these divs so let's go down here and we'll go right below the button Let's do an ID of result um and then I'm going to do a class of MTC six and text- XL so that will be the result we're not going to put anything in here because it'll get filled dynamically and then let's do our indicator so we'll have a class of HT mx- indicator and then let's do an ID of loading and then again I'm just going to use my image let's do um margin Auto and h-10 and image slash loading or loader. GI all right so at the moment if I click convert and 32 I just have that in here by default but it's not showing anything but it is making the request so if we look down here you can see every time I click it it's making the request we're just getting a 404 because it doesn't exist so let's create that endpoint we'll go in the back end here and let's say handle post request for uh I guess for temp conversion so it's going to be a post request so we want to do app. poost and the URL is going to be convert and let's add request response now I'm going to do the same thing with the set timeout just so we can see the um the image the the loader so we'll say set timeout let's [Music] do have our function and then let's do two seconds here so 2,000 milliseconds and then in here we're going to let's say Fahrenheit Fahrenheit I think that's how you spell it right yeah so Fahrenheit and then I'm going to parse this as a float so let's say parse float and in here to get the the data that's in here in this case that 32 we can do that with request. body Dot and then whatever the name is which is Fahrenheit right if we look at the input it has the name of Fahrenheit and in order to get data from the body you do have to have the middleware that I added earlier so that'll get the fahrenheit now for the Celsius let's say con Celsius and the conversion for that is going to be the fahrenheit minus 32 and then that's going to be multiplied by 5 / by 9 oops that should be slash okay so that should give us the Celsius then what I want to send back so let's say res. send and I'm going to send back uh template string and let's put this in a par graph okay and then I'm just going to to put the fahrenheit so we'll say Fahrenheit degrees uh Fahrenheit is equal to and then we'll have the Celsius value Celsius and I'm just going to add two fixed with two decimal places and then say degrees uh Celsius all right yeah that should do it so let's save that and then come over here reload I'm going to keep 32 in there I click it waits 2 seconds and then we get 32° fahren is equal to 0° CI if I change that to let's say 50 and we get 50° is equal to 10° C all right I guess we don't really need the the two fixed you can keep it if you want but I think it looks kind of weird so we'll get rid of that all right cool so that's just another example I and I figured I'd just show you guys that to show you uh using a different element we're using a form with a different trigger and a post request over a get request now another thing we can do is polling so this is where we can make a request to the server every so often to get updated data so if we want to set it to every 5 seconds or every 30 seconds or whatever so let me give you an example of that now I do want to save this so I'm going to copy it and inside public I'll create a new file here I'll just call it uh temp. or temperature say temperature. HTML paste that in save it and then in the index I'm just going to uh let's see yeah we'll just get rid of everything in the body and get rid of that class okay so I'm going to give you a very simple example of polling to begin with and then we'll do like a little weather app or a mock weather app that will fetch from the server every 5 Seconds the weather so that it'll it'll change automatically but first we'll do just kind of like a simple counter example so in body let's create let's just say text- Center and I'm going to have a span here uh I want to make this I want to make a get request so I'm going to use HX dget and I'm going to set that to SL pole okay that's the end point we're going to hit and then for the trigger this is how we can make it poll is we can say trigger and I'm going to set it to every every 10s so every 10 actually let's do five make it a little shorter so every 5 seconds so basically what will happen is it'll hit this SL Pole every 5 seconds and then it will replace whatever that response is into this span of course we could put it wherever we want if we want to use a Target or whatever and I'm just going to say loading to begin with all right so now let's go to our server and let's add let's say handle get request for uh polling example so app.get and SL Poole and all I'm going to do here is I'm going to set I'm going to start off with just a counter variable I'm going to put that outside of the route so I'll say let counter set that to zero and like I said This Server file is is kind of messy if you want to split it up into separate files you can do that and then I'm going to take that counter in here and just increment it by one and then so basically just simulating you know updated data and then let's say const data and we'll send back just a an object with a value of whatever that counter is and then we can actually just res. Json I mean normally you wouldn't put Json right in the browser but it's just an example so if we come over here and reload we see loading and in 5 seconds it should make another request so now we see value one I know that's really small hopefully hopefully you guys can see that but um Oops why is there we go so value three so every time it hits the server this counter is updating by one so that's just a very uh simple example of polling now let's make it a a little cooler and create like a a mini weather app so what I'll do is we'll do the backend first so let's say um we'll say handle handle get requests for for weather I don't know yeah that's fine so let's say app.get and let's call this get Dash temperature all right and then request response and this is going to be very simple I'm not going to actually reach out to a weather API although you could if you wanted to but I'm just going to generate a random Celsius temperature so let's say current actually I'm going to Define this outside of this so let current temperature set that to 20 by default and then here we'll say current temperature and we'll add a pend so plus equals math. random and we're going to multiply that by two and minus1 so that will just be a random temp change and then I'm just going to respond from this route so res. send and what I'm going to send is that current temperature value I'm going to add two fix to add add one decimal place and then just concatenate on the Celsius uh let me just grab the degrees symbol I'm just going to add that onto the end of it now let's go to our index HTML and instead of hitting pole we're going to hit get temperature and we'll we'll stick to every 5 seconds and I'm just going to make this look a little better let's add a couple classes I'm just going to paste these classes in actually okay and then I'll just add a heading above the span Let's do an H1 we'll say text- XL margin bottom four and we'll say weather in New York and then I'm going to just wrap this down here in a paragraph and let's do text- 5xl because I want that to be really big so we'll move that span into the parag graph all right so let's reload and now weather in New York it's loading and in 5 seconds let's see something's going wrong here did I spell something wrong oh I forgot my slash here let's try that so reload and 5 Seconds there we go so 19.9 Celsius and then in another 5 Seconds it'll check again now it's 20.7 so obviously this isn't the real weather we're just simulating it uh you could connect this to a weather API if you wanted to do that and you'd have it you know updating in in real time basically okay so that's polling now let's create a a cool little Search widget where we can search for users through an input through a text field and we'll have it fire off the requests every time we we push down a key all right so let's go into index HTML I'm just going to grab this here and we'll put this into uh I'll call this polling HTML paste that in save it and then we can get rid of this stuff here um I'm just going to keep the class of BG blue 900 and I might as well just grab the HTML for this and I'll just paste that into thex body save that reload all right so we just have this this search interface and let's just go over it real quick so we just have a container it kind of gave it a dark dark mode look um then we have the input which I haven't done any HTM X attributes yet we just have uh type name um table so basically what we want to do is fill this table fill the table body with the results so you can see the table body has an ID of search results so that should be our Target so let's go to the input and let's see we'll just add on under the placeholder here I'm going to make this a post request so we'll say HX post and we want it to go to slash search and then let's add a trigger so trigger now for this I'm going to say trigger on input changed and then you can also add a delay since we're doing it as we type we might want to add a little delay we can say 500 milliseconds and then add search all right so this should make a request every single time we we type something and then the target so HX Target so this is where the the response will go and that's going to be the ID of search results which we have below and then we'll go ahead and do an indicator on this as well so I'll set that to let's say loading and then I'll put the indicator up here up top so let's go right under the container and we'll say span class HTM X indicator and ID of loading and then I'm just going to use my image so we'll give it a couple classes here IMG loader loading all right so yeah I think that's really all we need for for the front end so you can see just how simple this is if you were to do this with vanilla JavaScript you'd have to select you know select the Dom elements and then add the event listner and then make the requests using fetch this is very simple so on the server side um we're going to go ahead and add the route for this so let's say handle post request for user search so it's a post request and it's going to be slash Search and say request response so as far as the the users uh I should say contacts it's like a contacts thing so we'll say for contact search I'm going to just create an array of contacts in fact I'm going to paste it in just because it's I have quite a few here and then I'll show you how we can refactor it to use Json placeholder like we did with the other one so we have these contacts I'm going to get the the text that's passed in here and call it search term so let's say con search term we can get that with request. body Dot and then search CU that's what I called it that's the name and I'm just going to make it to lowercase okay so that'll get the search term let's check to see if there's not a search term so if there's not then what I'm going to return is just going to be um let's say res. send and I'm just going to return an empty table row right because I don't want anything to show up if there's no search term otherwise when we clear it it'll show all the users all the contacts then after that let's perform a basic filter or basic search so we'll say search results and I'm going to set that to the contacts array and then we're going to use the filter method so here we'll say for each contact let's say con name and we can get that with con contact. name and I'm going to make it to lowercase and then I'll do the same with email because we want to be able to search the email as well then what we can do is say return and just in parenthesis here I'm going to say where the name includes the search term okay or let say or the email includes the search term uh yeah that should do it um now I I'm going to simulate a delay like I've been doing with set time out so under the search results let's say set timeout you don't have to do this uh I just I like how it looks with the loader but you don't have to do this um let's do we'll do 1 second so 1,000 now in the set timeout I'm going to create another variable here called search results our search result HTML and we're going to set that to our search results which is an array we're going to map through or Loop through that with map and say for each contact then let's return in backtick a table row so we have our table row and then two columns so we're going to have a TD uh TD and inside that uh I want to add a little bit of space inside of the column so I'm also going to have a div in here with my4 and padding two and then inside that is where we're going to put the contact. name copy that down and then we want the contact email so for each contact it should show the name here and the email here all right and since that's an array we just want to add onto that so onto this map I'm going to say do join turn that to a string and then finally we want to send so under that let's say res. send and we can send our search result HTML all right let's try it out so if we look at our users we have like John and Jane Doe so if I put a J in here okay so something's going wrong let's see uh request body search lowercase is not a function oh this should be an uppercase C okay so I'll type J we see our spinner and there we go now the spacing isn't showing for some reason and that's because this should not be class name we're not in react and yeah that should do it so J yeah if I put an O after it see it's going to make the request again and it comes back with just John do all right now they all have example.com in the email so if I do like ex then we should get all of them so it's a nice little you know real time search now again I know that this is going to be more backend but I want to make it so we're searching the users of the Json placeholder API so I'm going to create a separate route for that so I'll copy all this because it's going to be similar but I want to have both routes so I'll paste that in and then just change it to handle post requests for contact search from uh Jason placeholder so I'm going to change the the route here to search SL API now we want the search term right and then we want to check to see if there's no search term and then above where we're getting the results and filtering them we want to make the request and we could actually just copy what what we did up here so just get the response get the users so now just put that here except I'm going to change users we'll call it contacts because that's what we C called it down here all right so let's save that and then let's go into our front end and instead of SL search it's going to be SL search API so now if I reload that and I put an L in here uh let's see what's going on here did I not oh limit is not defined so we want to just take that out this right here all right that should work see L yep so now it's getting all the anything that contains L let's pass in E okay that NS it down a that NS it down to just lean all right so I do have some other projects um I think maybe we can do one more so let's do some inline validation so we'll have a form where we want to validate and uh we'll validate the email address to make sure it's formatted correctly and we show the message directly under that input so let's go to index HTML and I'm just going to copy everything from that file let's create a new file here we'll call this one search. HTML paste all that in save it all right so now we can get rid of everything in the body okay get rid of the body class now again I'm just going to grab the HTML for this and we'll go ahead and paste that in here see what that looks like all right so just basic form and what I want to do is have it so as we're typing it validates the email or not as we're typing but as we click outside of it or into another field it should say that email or please enter a valid email or that email address is valid okay so what you would normally do is have you'd have like a a HX post on the form for the submission but I'm not really concerned with the submission I want to make a separate request to validate the email address um now we're doing that on the back end and normally what you would probably do is check to see if that email exists in a database and then you know have have it say that email already exists or whatever but we don't have a database so we're just going to do some just a basic validation of an email so let's add onto the input here so this input with the name of email I'm going to add HX dpost and set that to slash contact slail because you might have the form actually submit to SLC Conta this is separate this is just for validation um now as far as you know where I want to put this let's go to the div um yeah let's go to above the label this div right here and let's add onto this HX D Target and let's set that to this so this element and then I want to swap so HX D Swap and we'll set that to Outer HTML I think that should do it so now if we just check it out make sure that the request is being sent right if I reload this click in here I type something and then I click outside of it then it's making that request okay and obviously we haven't created it yet we haven't created the route so let's do that we'll go to our back end here and let's add let's say handle uh handle post request for email validation so app. poost and it's going to be slash Conta slil so first thing I'm going to do is get the submitted email so we'll call this submitted email and we'll set that to request. body. mail okay so that'll give us whatever is typed in then I want a regular expression to to match against to make sure the email is valid so I'm just going to paste that in definitely not typing out that regular expression but it's just a simple expression that'll match a a you know an email address then we'll have some messages that we want to send if it's valid or not so let's say const is valid and I'm actually going to set that to an object that has both a message and a class because I want it to be red if it's an error and green if it's not so let's say message and we'll say that email is valid and then we'll add a class of text- green d700 and then for the if it's not valid then let's call this is invalid and the message will say let's say please enter a valid email or email address and we'll change the color to text red 700 all right so we have our messages now we want to do the test so let's say if so if not email um what did I call that email re reg X so reg X and then we can test that so we can use the do test method and pass in submitted email because that's what we want to test it against so if that's true then let's return res. send and then some back ticks now remember we're rep replacing that whole div right because this div right here is what I'm replacing and that's going to include everything in it so let's grab that right so that ends right here it includes the label and it includes the input so I'm going to paste that in here and then what do we want to change if it's valid we're going to first of all add the value because we want the value to stay in the input so on the input let's do value and we're going to set that to the submitted email so let's say submitted email and then underneath let's see we're going to go underneath the input and that's where we'll have the message so let's create a div and I want that the class cuz remember it's a it's a dynamic class it'll either be red or green and we can get that by let's say uh is so if it's not so this is if it's not valid so we want is invalid. class and then inside here is where we'll have the is invalid. message right because we're saying if it if it's not this if it doesn't match so then in the else let's say else so if it does match we're going to do something very similar so I'll just grab this whole thing and paste that in and we're going to keep the value there and then just change this to is valid class and then is valid message all right and that should do it so now I'll go ahead and reload and I'm going to just type in test and if if I click outside of it we get please enter a valid email address if I do test at test.com and I click outside of it we get that email is valid okay so it's just it's just inserting this block of code inside of this the div right where we targeted it and it's either going to be valid or not now again this is we're doing this on the back end this would be common if you were checking to see if an email existed or not in a database but like I said we don't have a database I mean I guess we could have just mocked it but this is fine as well it just the point is to show you how HTM X works right so again no JavaScript at all here and we're dynamically replacing parts of our page without having to reload it that's the whole point of this so again you're very dependent on a back end I know we wrote quite a bit of of serers side JavaScript here but we didn't write any at at all in any of these HTML files on the front end all right so um I think that that's where I'm going to stop I do have a couple other small projects I'm going to include those in the repository I think I have one or two other ones one is like a mini profile that you can click to update so you click it and then it's replaced with a form and then you can you know save your details um and obviously in real life you'd have that connected to a database but hopefully this just gives you some ins it onto some some of the reasons why you would use HTM X um and again it's really popular with LA not laravel uh Jango although you could use it with laravel of course or or anything at all um but that's it guys I hope you enjoyed this and learned something from it and I will see you in the next video
Info
Channel: Traversy Media
Views: 99,203
Rating: undefined out of 5
Keywords: htmx, htmx tutorial, htmx crash course, hyperscript, hyperscript attributes, node.js, node express, express.js
Id: 0UvA7zvwsmg
Channel Id: undefined
Length: 56min 46sec (3406 seconds)
Published: Mon Jan 01 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.