I've seen a lot of people experiencing errors when attempting to input a URL to go to a page. If you are experiencing errors, make sure your server is only serving your index page for any request. This will allow your router to load and operate properly. Apologies for not including that part in the video!
Hello Mitch , this looks really cool. can you tell me if we have three forms into these three paths , and a single submit button to post data to server , will it be possible to make it like that ? I have a small use case to develop so that’s why wanted to check with.
This 3 minute clip just saved me from learning Angular, React, Node.js and TypeScript. I know there are quite a bit differences, but for my purpose this is exactly what i needed, thanks! :D
Such a straightforward implementation of vanilla JS routing. THANKS! i had already looked at several tutorials attempting the same. They were across the board clunky and, at times, arcane (at least to me). You saved me many hours of frustration and aggravation.
Great video, Mitch Dev. Thank you for such a nice and simple video! It's much better to get everything you need for less than 4 minutes than watching my professor's 1.5h lecture which would give me no idea what is going on.
still cant get why do we need route function Looks like ive got why we need route function. So if we have buttons then we just set click event on them and call route function in callback function, right?
Thats because when you input the URL into the browser, it is actually making a http request to the server. But since is only client side it will not work
you probably need to set up your web server (in my case I use Apache, so .htaccess) to use your main index.html page as the 404 page. You're basically always 404'ing, but then handling it by serving up your web app.
It's so nice, clear and perfect this video. However, I would like to know what will happen if we refresh the page ? i.e « If I'm on (about page) then I refresh, it will go back (to index page) ? »
What are you using to host your local server? I'm using the VSCode extension Live Server and reloading the page or manually entering a path causes an error
I also use the live server extension. If you cloned the repo, it should work out of the box if you start the live server on the root html page. If you're recreating it for yourself, make sure your route paths are correct
@@katarca1120 funny thing is I have tried a similar approach with pushState and popState with a node server but manual url entry or refresh works. I still haven't found a solution for this.
very nice! though your example does not demonstrate the advantages of client-side routing over server-side routing? fetch still grabs the entire contents of the 3 pages, every time a link is clicked?
Edit: Solved - if you are using webpack, remember to set historyApiFallback: true, in the devServer Hey Mitch, how can I serve the right page to the URL on page refresh? For example if I navigate to /blog and refresh the page I would get a 404. I have set things up with webpack and all seems to work, just not on page refresh. Cheers
how about loading scripts when loading those other html files? I am having a problem with setting innerHTML and the JS not working with fetched HTML files.
Very concise! I am confused where you’re fetching the html for each page from and how there are two const route variables initialized? Assume it has something to do with async/await concepts I haven’t learned yet 😂
Hello friend, I tried to use this method for a SPA and it worked perfectly, but when I want to use images as "a", the "oneclick" does not work and it is only possible to access the "a" by clicking around the img. But it doesn't work if you click inside it. Any advice on how to solve this? I have very little idea of js, so I'm stuck with this problem.
Because if we refresh page the route is different from home route is a big problem when you host the app but for this we have solution like longitude and something like like landude in angular using provider In javascript there is something like this using this you route is like this 'home/+your route ' using this it solve the problem
I removed it because found somewhere on the internet that it is a bad practice (creating global variables, through assigning them as global object/document properties).
I have a question, can i manipulate the dom with this method? for example i want to make an event listener so that when click the h1 element on the about page it logs "clicked" on the console. Been struggling with that.
Thanks for your video. From your code, I can see that handleLocation function is mannuallly triggered in route() function. where it should be triggered by pushState().
Hi Mitch, I understand this is a late comment, especially now that parcel-bundler has been replace with Parcel. I was having difficult perfecting the SPA in this video. Everything seems to work fine except when i enter the url via the browser address bar. Can you assist here, please.
This is great, but then how would we link a different javascript file to each html page so we could have an actual application logic instead of just views?
If you're building an HTML string in JS, you can just use the string generated when setting 'innerHTML'. You can define that functionality in another JS file and require it in your router to keep it clean if desired
For those who have problem when the page refresh while insert the url via the browser , the solution is to do the in the config of your web server, in my case nginx: location / { try_files $uri $uri /index.html =404; } In my case, this resolved this problem. Excuse my english, is not very good looking!
I am not. Could you give some suggestions? Where should i start? I should write my own server on node js and add server file to my repo? Is it correct?
A great it is, the answer of my problem. But now, there's a another problem when Refreshing my browser it's shows Error file not found. I hope there's something answer on it
hi, im working with python + flask on the backend. with the js file, im getting not found error when clicking the links. i think the issue lies in the const routes function. ive tried so many different paths but i cant get it to work
Wow great.. , well I want to implement to typescript , but I get some errors .. because some code I have null ..., well is possible transform to typescript ..? , but thank you.. nice code.
you should not use the .html for this little changes and get the whole html page (it's inefficient to do it), in exchange you could use the rest api for that and "refresh" the page. but it's a greate video!
This tutorial is just awesome, but in my case, when I refreshe the page in any of the routes (that is not the home), it just doesnt load.. I see the message: "Cannot GET"
Im curious why someone would do this instead of just creating some content within the same index.html and creating some function that renders or toggles that content as visible or not?
That is a 100% viable solution. The drawback to something like that is an extremely large index.html file if your site is to have a lot of content, which can be cumbersome to maintain. Fine for the user, bad for the developer. There is no 100% right or wrong answer when coming up with a solution for routing, they all have pros and cons
Yes, all requests should serve the root page. This allows the router to work as expected, and why some people may be experiencing errors when attempting to use the URL bar to navigate
@@NicoHeinrich You're right, I forgot I had that setting on my live server so didn't include it in the video (my bad!). I may do another video with the hash router, but I personally do not think it is a good design decision so we'll see on that one
Also, for the home page I don't use a link but a function that resets the url via pushstate (instead of linking to an empty hash). For it to work though you have to initiate your router function as well. Makes the hash router a lot prettier in my opinion.
I've seen a lot of people experiencing errors when attempting to input a URL to go to a page. If you are experiencing errors, make sure your server is only serving your index page for any request. This will allow your router to load and operate properly. Apologies for not including that part in the video!
u can make another one with this error.pleae.
you have link to movie that show how to do this?
I believe that is what the parcel-bundler is been used for, right?
Hello Mitch , this looks really cool. can you tell me if we have three forms into these three paths , and a single submit button to post data to server , will it be possible to make it like that ? I have a small use case to develop so that’s why wanted to check with.
can you explaine this point more plz
This 3 minute clip just saved me from learning Angular, React, Node.js and TypeScript. I know there are quite a bit differences, but for my purpose this is exactly what i needed, thanks! :D
I came here for the same reason and use htmx or alpinejs for reactivity
Such a straightforward implementation of vanilla JS routing. THANKS! i had already looked at several tutorials attempting the same. They were across the board clunky and, at times, arcane (at least to me). You saved me many hours of frustration and aggravation.
Making the clone of Spotify using only vanilla js , this is my favourite video , thanks bro, love from India
Great video, Mitch Dev. Thank you for such a nice and simple video! It's much better to get everything you need for less than 4 minutes than watching my professor's 1.5h lecture which would give me no idea what is going on.
OMG !!! This is the madness i have been looking, Long live Mr. DEV.
surprisingly, i found a very clear usecase of vanilla js for routing from non indian youtuber
Very good video and explanation. It was what I was looking for, a simple router in js vanilla. Thanks for sharing. I will be aware of the channel.
Wow, amazing!!!
OMG so clear, so to the point, so short, again wow
Excellent👏
Thank you for this great contribution, simple and perfect explanation.
is just that u need an extended knowledge of js to do this.... thank you very much
This vidéo is great ,direct and clear .
Thank's it helped a lot
Great video, I've been looking for a simple example like this, thanks for sharing.
Exactly what I was looking for, works great, you the man!
Man you are awesome... I was looking for this for very long thank you
Dope example. A bit too fast for those who are watching SPAs from scratch for the first time, but thanks a lot for the concise version.
thanks for the upload, clean and straightforward explanation! :)
This helped me a LOT! Thank you man.
Super excellent video for those like me who like to do most things by hand
awesome, simple and clear solution
Mitch, from now on, I follow you!
Great video! Real simple and to the point
thanks for the video, but there's an error when i reload after clicking one of the route nav, any ideas?
Simple way to kickstart a small webapp without all the crrap of framework and npm, etc.
still cant get why do we need route function
Looks like ive got why we need route function. So if we have buttons then we just set click event on them and call route function in callback function, right?
it only works when clicking the links, but error when doing it through URL
Thats because when you input the URL into the browser, it is actually making a http request to the server. But since is only client side it will not work
you probably need to set up your web server (in my case I use Apache, so .htaccess) to use your main index.html page as the 404 page. You're basically always 404'ing, but then handling it by serving up your web app.
Thank you so much for this awesome video 🙏
It's so nice, clear and perfect this video.
However, I would like to know what will happen if we refresh the page ?
i.e « If I'm on (about page) then I refresh, it will go back (to index page) ? »
What are you using to host your local server? I'm using the VSCode extension Live Server and reloading the page or manually entering a path causes an error
I also use the live server extension. If you cloned the repo, it should work out of the box if you start the live server on the root html page. If you're recreating it for yourself, make sure your route paths are correct
@@mitch_dev Same problem. I cloned the repo, but still if I manually enter a path it cause an error. I didn't figure out how to fix it.
@@katarca1120 haven't found a solution on this
Neither do I. I just want to point out that this is clearly not usable in practice.
@@katarca1120 funny thing is I have tried a similar approach with pushState and popState with a node server but manual url entry or refresh works. I still haven't found a solution for this.
How to have dynamic urls, like /blogs/1 for example?
THIS HELP SO MUCH! THANK'S
This is an awesome video. Thank You.👏
This is a very very well made video!
Thanks a lot man, you should upload more videos like this
very nice! though your example does not demonstrate the advantages of client-side routing over server-side routing? fetch still grabs the entire contents of the 3 pages, every time a link is clicked?
Edit: Solved - if you are using webpack, remember to set historyApiFallback: true, in the devServer
Hey Mitch, how can I serve the right page to the URL on page refresh? For example if I navigate to /blog and refresh the page I would get a 404. I have set things up with webpack and all seems to work, just not on page refresh.
Cheers
Great tutorial! Thanks!
how about loading scripts when loading those other html files? I am having a problem with setting innerHTML and the JS not working with fetched HTML files.
Awesome video.
Very concise! I am confused where you’re fetching the html for each page from and how there are two const route variables initialized? Assume it has something to do with async/await concepts I haven’t learned yet 😂
Hey @Mitch Dev, This is awesome, thanks for this video, just a question, Is this how all the SPA's have the router library built-on?
Hello friend, I tried to use this method for a SPA and it worked perfectly, but when I want to use images as "a", the "oneclick" does not work and it is only possible to access the "a" by clicking around the img. But it doesn't work if you click inside it.
Any advice on how to solve this? I have very little idea of js, so I'm stuck with this problem.
give the href and onclick to the img tag
This is a cool project, just a small problem. If I go to "/about" and refresh the page, it returns "Cannot GET /about"
You need to add redirect to home.
Because if we refresh page the route is different from home route is a big problem when you host the app but for this we have solution like longitude and something like like landude in angular using provider
In javascript there is something like this using this you route is like this 'home/+your route ' using this it solve the problem
What's the difference between this and a href or window. Replace?
Great explanation!
Great project man !!!
Please upload more such videos 😊
hi! tanks for the video.. have a problem with get elements in the DOM pages, any idea?
I use async functions for this.
that's beautiful
is window.route = route; neccessary? If neccessary, what for?
This is something I still struggle to figure out.
I removed it because found somewhere on the internet that it is a bad practice (creating global variables, through assigning them as global object/document properties).
I removed it but it causes the page to reload. Not sure how this is working
Simple et efficace 👍
Yeah bro its work thankyou
Hi Mitch, thanks for this video. Maybe could you do the same with a vanilla js created with vite?
Hi Mitch,
How do we send post requests, I have tried all things but does not work it returns html response
I have a question, can i manipulate the dom with this method? for example i want to make an event listener so that when click the h1 element on the about page it logs "clicked" on the console. Been struggling with that.
thank you very much
can u create a dynamic route in vanilla js ? example: /detail/:id --> show id in screen
Thanks a lot man
Awesome
Can I run this as a static website from S3 or does it need a server to render files?
Thanks a lot
wow! Wonderfu
greet job but what about go back URL?
Thanks for your video. From your code, I can see that handleLocation function is mannuallly triggered in route() function. where it should be triggered by pushState().
Here is a modified .js which works for me:
const route = (event) => {
event = event || window.event;
event.preventDefault();
// pushState method to update the browser's URL during page navigation.
window.history.pushState({}, "", event.target.href);
// To trigger window.onPoPState
window.history.pushState({}, "", event.target.href);
history.back()
};
const routes = {
404: "/pages/404.html",
"/": "/pages/index.html",
"/about": "/pages/about.html",
"/lorem": "/pages/lorem.html",
};
window.onpopstate = () => {
const path = window.location.pathname;
const route = routes[path] || routes[404];
fetch(route)
.then((res) =>res.text())
.then (html => document.getElementById("main-page").innerHTML = html)
.catch(error =>document.getElementById("main-page").innerHTML = 'unexpected error')
};
How i can use ejs instead html for SPA?
Hi Mitch, I understand this is a late comment, especially now that parcel-bundler has been replace with Parcel. I was having difficult perfecting the SPA in this video. Everything seems to work fine except when i enter the url via the browser address bar. Can you assist here, please.
I have the same problem, did you find a solution?
On refresh. throws error, with no content.
Hi what about the parameters in url routing to a specific page like single page or a blog page
How can we write a localhost without any framework or packages in vanilla Javascript? I can nowhere on the internet on how to do that?
This is great, but then how would we link a different javascript file to each html page so we could have an actual application logic instead of just views?
You can add a tag inside of each html file
@@zodeyack1 I tried this, it doesn't work :(
U should use js modules instead. Connect all modules to main.js with import/export keywords.
Thank you
What should I do or change if I want to use js modules (smth.js which build html page) instead of using .html files?
If you're building an HTML string in JS, you can just use the string generated when setting 'innerHTML'. You can define that functionality in another JS file and require it in your router to keep it clean if desired
how if in html run javascript fuction and fetch api? like product page?? please tutorial?
For those who have problem when the page refresh while insert the url via the browser , the solution is to do the in the config of your web server, in my case nginx:
location / {
try_files $uri $uri /index.html =404;
}
In my case, this resolved this problem.
Excuse my english, is not very good looking!
Does anyone how i can make it work on GitHub pages? Its working fine on my local after editing the live server settings
Familiar with Node JS?
I am not. Could you give some suggestions? Where should i start? I should write my own server on node js and add server file to my repo? Is it correct?
A great it is, the answer of my problem. But now, there's a another problem when Refreshing my browser it's shows Error file not found. I hope there's something answer on it
I did it all , links are working but when I add '/about' to my website url it says page not found 404 ( not my own 404 page )
thanks for the tutorial. unfortunately on refresh it throws a "Cannot GET" message
Heeelp!!, How can I use it with parameters?
window.event is deprecated, I don't found any alternative.
What does window.route = route do?
hi, im working with python + flask on the backend. with the js file, im getting not found error when clicking the links. i think the issue lies in the const routes function. ive tried so many different paths but i cant get it to work
you must redirect all requests to the index, or forget about that and use #hashes instead /#about
@@Nodsaibot can you give a snippet to show how to redirect to the index based on the code provided? Thanks
Wow great.. , well I want to implement to typescript , but I get some errors .. because some code I have null ..., well is possible transform to typescript ..? , but thank you.. nice code.
that URL scheme will cause 404 errors, you need to rewrite all requests to the index or redirect 404s to the index, or just use Hashes instead
can you give a snippet to show how to redirect to the index based on the code provided? Thanks
how are u hosting the html on local server ?
you should not use the .html for this little changes and get the whole html page (it's inefficient to do it), in exchange you could use the rest api for that and "refresh" the page.
but it's a greate video!
Yes, but instead of calling fetch, use your class to prepare your template and set inner html in root 🙂
what?
This tutorial is just awesome, but in my case, when I refreshe the page in any of the routes (that is not the home), it just doesnt load.. I see the message: "Cannot GET"
Thx.
no matter what I do, it will navigate to the other page loosing everything.
Спасибо
Im curious why someone would do this instead of just creating some content within the same index.html and creating some function that renders or toggles that content as visible or not?
That is a 100% viable solution. The drawback to something like that is an extremely large index.html file if your site is to have a lot of content, which can be cumbersome to maintain. Fine for the user, bad for the developer. There is no 100% right or wrong answer when coming up with a solution for routing, they all have pros and cons
Do I still have to redirect all requests to the root?
Yes, all requests should serve the root page. This allows the router to work as expected, and why some people may be experiencing errors when attempting to use the URL bar to navigate
@@mitch_dev I think you don't make it clear enough (if at all) in your video. Maybe make a second video with the # method as well.
@@NicoHeinrich You're right, I forgot I had that setting on my live server so didn't include it in the video (my bad!). I may do another video with the hash router, but I personally do not think it is a good design decision so we'll see on that one
@@mitch_dev it definitely is less aesthetically pleasing but also less restrictive and way easier to implement.
Also, for the home page I don't use a link but a function that resets the url via pushstate (instead of linking to an empty hash). For it to work though you have to initiate your router function as well. Makes the hash router a lot prettier in my opinion.
Load big html css it goes slow
I wanted かめりあ - Routing SPA what is this youtube
how we can implement an individual detail page, for examples for every of 100 posts
Vanilla js routing
Не удалось скачать видео
is it seo friendly ?
Not everything is frameworks!