Vanilla JS Single Page Application Routes | # or URL - #88

Поделиться
HTML-код
  • Опубликовано: 1 июл 2024
  • #spa #vanillajs #hash #routing #tutorial
    One of the most asked code questions during a front-end interview is "Can you create a single page application with routes, without a framework?" In this tutorial, I show you how to create a custom routing system for your single page application using either the hash or URL method...without a framework.
    This tutorial shows you how to build a Single Page App using vanilla JavaScript. I show you how to implement client-side routing both ways (hash or URL) in an easy-to-use format that can be replicated for any project.
    So, let's get started with our Single Page Application.
    00:00 Intro
    01:07 Creating our index.html
    04:55 URL-based routing
    17:13 Potential issues with URL routing
    21:08 Setting titles and meta description
    25:25 Add hashed HTML URLs
    26:57 Hash-based routing
    32:05 Testing both methods
    View on GitHub: github.com/thedevdrawer/spa-r...
    ⭐ If you would like to buy me a coffee because I created something that helped you, it would be much appreciated! : www.buymeacoffee.com/devdrawer
    ⭐ Join this channel to get access to perks:
    / @devdrawer
    ⭐ Become a Patreon to show support and get exclusive access to content: / devdrawer
    `````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
    Subscribe: bit.ly/2Wbsnj9
    `````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
    Join us on our blog for video recaps and other tutorials: thedevdrawer.com
    Become a fan on Twitter: / thedevdrawer
    View Project on GitHub: github.com/thedevdrawer
  • НаукаНаука

Комментарии • 68

  • @DevDrawer
    @DevDrawer  2 года назад +4

    Don't forget to check out the code on GitHub if you are having issues. After you watch, let me know which routing method you prefer.

    • @Alex-gn3vm
      @Alex-gn3vm 2 года назад

      Good day! Thank you for this content! It `s the best what i see about vanilla JS! But i have one moment. When i change page, some javascript and jquery dont`t work. Can you say how solve the problem of work another scripts? Thank you!

    • @DevDrawer
      @DevDrawer  2 года назад +2

      So you have to keep in mind that this script pretty much runs everything 1 time so if your "Query or JS " element being referenced is not loaded on the page you are on first, then the JS does not see it.
      For example, if you load the home page, the script will run. Once you click to the about page the script has already run but now you have a button click event coded, well that button did not exist on the first script run.
      You can get around this by adding your events for other jquery or js into a DOMContentLoaded event listener.
      For example:
      document.addEventListener("DOMContentLoaded", () => {
      $(function(){
      document.querySelector('#test').innerHTML = "test";
      });
      //run router again
      });
      I have not tested the code, but basically your code is no longer loaded because $(function(){}) is loaded on page load so any functions or events contained within that are not being run because the content of the page is dynamic and not being refreshed.
      Lastly, keep in mind this SPA routing is for simple applications so if you are trying to integrate this into a larger or more complicated project it may fail. The goal was to create a simple router without a framework. In your case, you may need a framework that can handle DOM manipulation.

  • @robertoportfolio1378
    @robertoportfolio1378 2 года назад +21

    Yes finally... a person who can code in Javascript and not using frameworks and libraries

    • @DevDrawer
      @DevDrawer  2 года назад +5

      Glad you liked it. I honestly use frameworks too but vanilla js is just as powerful if you know how to use it.

  • @de_castilho
    @de_castilho 3 дня назад

    dude, this is the best video that i saw about simple js SPA.

    • @DevDrawer
      @DevDrawer  3 дня назад

      That is awesome to hear. Thank you.

  • @solomonnwabuoku162
    @solomonnwabuoku162 2 года назад +5

    Watched alot of tutorials on routing but didn’t understand till i came across yours. Dope stuff

    • @DevDrawer
      @DevDrawer  2 года назад +2

      That's awesome. I am glad you learned something.

  • @CoreDreamStudios
    @CoreDreamStudios Год назад

    Subscribed! This was very useful and a good way to get started in vanilla JS with this kind of templating.

    • @DevDrawer
      @DevDrawer  Год назад

      Thanks for the subscribe. I am glad you liked the video.

  • @EduardoLopez-us5gs
    @EduardoLopez-us5gs 4 месяца назад

    Thanks man!, Learned a lot, simple and to the point on vanilla!

    • @DevDrawer
      @DevDrawer  4 месяца назад

      That's awesome. Thanks for the watch

  • @user-lh9gu1fc9u
    @user-lh9gu1fc9u Год назад

    Thank you for this, straight forwards .

    • @DevDrawer
      @DevDrawer  Год назад

      Glad you liked it. Thanks for watching

  • @ariel18012
    @ariel18012 Год назад

    Muy buen video amigo, para entender JS sin el uso de framework esta excelente,
    ojala puedas agregar traducción al espaniol en tus videos, sigue así.

    • @DevDrawer
      @DevDrawer  Год назад +1

      Gracias por ver y aprender algo. No hablo español, así que no sé si puedo traducírtelo. Lo lamento. Traducido de Google.

  • @riccarrasquilla379
    @riccarrasquilla379 8 месяцев назад

    thanks for the tutorial

    • @DevDrawer
      @DevDrawer  8 месяцев назад

      No problem glad you enjoyed it

  • @TimeStampHero
    @TimeStampHero 8 месяцев назад

    Thank you!

    • @DevDrawer
      @DevDrawer  8 месяцев назад

      Then you for watching

  • @d-a-m-i7439
    @d-a-m-i7439 2 года назад

    you have a +1 subscriber today
    🥰🥰🥰

    • @DevDrawer
      @DevDrawer  2 года назад

      Thanks, I am glad you liked it

  • @ashrafulrahmansakil9612
    @ashrafulrahmansakil9612 2 года назад

    Nice

  • @stadtminish3219
    @stadtminish3219 3 месяца назад

    Thanks for your script. I can use this well for my applications.
    But I'm a little confused. I always read that you should avoid global variables. But it seems to work so much easier. Unfortunately, when I tried to convert my Javascript code into modules, I failed miserably. It would be interesting to see a modular router.

  • @Alex-gn3vm
    @Alex-gn3vm 2 года назад

    Good day! Thank you for this content! It `s the best what i see about vanilla JS! But i have one moment. When i change page, some javascript and jquery dont`t work. Can you say how solve the problem of work another scripts? Thank you!

    • @DevDrawer
      @DevDrawer  2 года назад +1

      So you have to keep in mind that this script pretty much runs everything 1 time so if your "Query or JS " element being referenced is not loaded on the page you are on first, then the JS does not see it.
      For example, if you load the home page, the script will run. Once you click to the about page the script has already run but now you have a button click event coded, well that button did not exist on the first script run.
      You can get around this by adding your events for other jquery or js into a DOMContentLoaded event listener.
      For example:
      document.addEventListener("DOMContentLoaded", () => {
      $(function(){
      document.querySelector('#test').innerHTML = "test";
      });
      //run router again
      });
      I have not tested the code, but basically your code is no longer loaded because $(function(){}) is loaded on page load so any functions or events contained within that are not being run because the content of the page is dynamic and not being refreshed.
      Lastly, keep in mind this SPA routing is for simple applications so if you are trying to integrate this into a larger or more complicated project it may fail. The goal was to create a simple router without a framework. In your case, you may need a framework that can handle DOM manipulation.

  • @user-pq3fg9ps3k
    @user-pq3fg9ps3k Год назад

    I have hash routing working but url routing not working. Can anyone help how to set up environment for url routing, locally or on openserver doesn't work

  • @WallyAtkins
    @WallyAtkins Год назад +2

    Would you mind posting an example of a .htaccess on the GitHub repo when you get a chance?

    • @DevDrawer
      @DevDrawer  Год назад +1

      I added a simple htaccess file to the repo: github.com/thedevdrawer/spa-routing
      You turn on the rewrite engine, then add symbolic links and multiviews, then finally, rewrite everything to index.html.
      If you want to learn more tips and tricks with your htaccess file, you can find it in these videos:
      Video 1: htaccess, Directives You Need to Know: ruclips.net/video/mD3jrHZ3gUw/видео.html
      Video 2: htaccess, Advanced Tips and Tricks: ruclips.net/video/aU48yQHh9q4/видео.html

  • @valentinav8585
    @valentinav8585 2 года назад

    Great! Amazing! But how do I go about adding more JavaScript? Let's say I want to add an alert in one of the pages or whatnot, or fetch some items from a JSON and put them in another page ..using document.querySelector doesn't work, I guess it's because the page needs to load first 😥 I feel like I must be missing something but I can't figure it out
    So close to giving up and just going for react instead 😪

    • @DevDrawer
      @DevDrawer  2 года назад +1

      So you have to keep in mind that this script pretty much runs everything 1 time so if your "Query or JS " element being referenced is not loaded on the page you are on first, then the JS does not see it.
      For example, if you load the home page, the script will run. Once you click to the about page the script has already run but now you have a button click event coded, well that button did not exist on the first script run.
      Try something like this:
      document.addEventListener("DOMContentLoaded", () => {
      document.querySelector('#test').innerHTML = "test";
      //run router again
      });
      I have not tested it, but that should put you in the right place to have the JS listen for document changes. I hope this helps.

    • @valentinav8585
      @valentinav8585 2 года назад +1

      @@DevDrawer ay thank you I will try later on! Did my thing in react for now but Im definitely eager to work more in vanilla for simple projects!

  • @toba-bonjour
    @toba-bonjour 4 месяца назад

    Thanks man! Will I get errors when attempting to input a URL to go to a page ?

    • @DevDrawer
      @DevDrawer  4 месяца назад +1

      You shouldn't. It should load based on the route.

  • @mauriciolaratro
    @mauriciolaratro Год назад

    Good day bro!
    First of all, thanks for the content and the good explanation.
    I tried to apply the solution you gave above to the problem with scripts on pages other than home, which worked for me but for it to work I have to go to the page that has the content that I point to with the script and refresh the page.
    Would you know what could be the problem and its possible solution?

    • @DevDrawer
      @DevDrawer  Год назад

      I added this as another comment but maybe it will help you:
      So you have to keep in mind that this script pretty much runs everything 1 time so if your "Query or JS " element being referenced is not loaded on the page you are on first, then the JS does not see it.
      For example, if you load the home page, the script will run. Once you click to the about page the script has already run but now you have a button click event coded, well that button did not exist on the first script run.
      You can get around this by adding your events for other jquery or js into a DOMContentLoaded event listener.
      For example:
      document.addEventListener("DOMContentLoaded", () => {
      $(function(){
      document.querySelector('#test').innerHTML = "test";
      });
      //run router again
      });
      I have not tested the code, but basically your code is no longer loaded because $(function(){}) is loaded on page load so any functions or events contained within that are not being run because the content of the page is dynamic and not being refreshed.
      Lastly, keep in mind this SPA routing is for simple applications so if you are trying to integrate this into a larger or more complicated project it may fail. The goal was to create a simple router without a framework.

    • @mauriciolaratro
      @mauriciolaratro Год назад

      @@DevDrawer Yes, this is the solution I tried to apply, after seeing your comment. But it only works once the page is reloaded.
      Would you know what could be the problem?
      Maybe I'm just misapplying the solution script, sorry for the inconvenience.

  • @kittcheung8424
    @kittcheung8424 2 года назад +1

    I went and tried to do this for my webpage but it didn't work. Whenever I click on (in my case) "Products" it shows that message you were mentioning about "Cannot GET templates/products" what did I do wrong? I followed the video.

    • @DevDrawer
      @DevDrawer  2 года назад +1

      If you are using the URL Routing method, you need to make sure you have your .htaccess handling the index.html render. The URL method only works if you are telling the server that it needs to display all content in the index.html file.
      I give 2 options: URL and Hash. Only the URL method requires this. There are some downsides to using this method. You need to configure the webserver to serve the index.html for SPA Route Paths. You can do this at the server level but if you are using something like VS Code LIVE SERVER, you cannot. This means if you navigate directly to /about the server will not render the file as it needs to load the index.html scripts first. You can modify your .htaccess file to accomplish this.
      Try adding something like this to your .htaccess file:
      DirectoryIndex index.html
      This will force your server to see the index.html as the directory file. If this is not possible, the second method using hashing may be better for your situation.

  • @GerunMatt
    @GerunMatt 2 года назад +1

    In mozilla's JS documentation said that "window.event" is decprecated ..

    • @DevDrawer
      @DevDrawer  2 года назад +1

      That is more of a fall back and can be removed as it will most likely not have been used in the execution of the JS anyway. Good catch.

    • @simonnsolomon
      @simonnsolomon 11 месяцев назад

      @@DevDrawer the tutorial is helpful and I liked it, however I faced the same problem and I tried removing window.event but it doesn't route to other pages, can you please help?

  • @moxopixel
    @moxopixel Год назад

    How does this work with hosting in a subfolder?

    • @DevDrawer
      @DevDrawer  Год назад

      Should work the same way using a script src relative to the subfolder. I have not tried it like that but I would assume it would work as is or with slight modifications to the routing.

  • @Chlorine-DB
    @Chlorine-DB 5 месяцев назад

    I'm no expert when it comes to Js but i'll ask anyway, is there any reason why you used the || operator instead of the ?? operator here 08:20? as far as i know it's better to use this one '??'.

    • @DevDrawer
      @DevDrawer  5 месяцев назад +1

      They both kinda do the same thing in this instance so it is probably more of my background in PHP bleeding over. It would be better to use the ?? usually since it chooses left or right depending on null values but like I said for this instance either would work.

    • @Chlorine-DB
      @Chlorine-DB 5 месяцев назад

      @@DevDrawer That makes sense, i just had a doubt, thanks for responding!

  • @user-sz2qq4bz3r
    @user-sz2qq4bz3r 2 года назад

    how we can implement an individual detail page for example for many posts?

    • @DevDrawer
      @DevDrawer  Год назад +1

      This is more for simple page routing. In order to use more dynamic routing, you would have to modify the script to handle variables like ID or page name. This script is more 1-to-1 routing. It is possible, but honestly, if you are looking for something with dynamic routing it may be better to use something like React or Vue. Once you get into dynamic variables, it complicates the vanilla JS part of it 1000%.

    • @user-sz2qq4bz3r
      @user-sz2qq4bz3r Год назад

      @@DevDrawer thanks a lot!

    • @DevDrawer
      @DevDrawer  Год назад

      Sorry I wasn't more helpful, but hopefully that points you to the right path.

  • @jordanfox3782
    @jordanfox3782 2 года назад

    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?

    • @DevDrawer
      @DevDrawer  2 года назад +1

      I answered this in another comment, but it may help you as well:
      So you have to keep in mind that this script pretty much runs everything 1 time so if your "Query or JS " element being referenced is not loaded on the page you are on first, then the JS does not see it.
      For example, if you load the home page, the script will run. Once you click to the about page the script has already run but now you have a button click event coded, well that button did not exist on the first script run.
      You can get around this by adding your events for other jquery or js into a DOMContentLoaded event listener.
      For example:
      document.addEventListener("DOMContentLoaded", () => {
      $(function(){
      document.querySelector('#test').innerHTML = "test";
      });
      //run router again
      });
      I have not tested the code, but basically your code is no longer loaded because $(function(){}) is loaded on page load so any functions or events contained within that are not being run because the content of the page is dynamic and not being refreshed.
      Lastly, keep in mind this SPA routing is for simple applications so if you are trying to integrate this into a larger or more complicated project it may fail. The goal was to create a simple router without a framework. In your case, you may need a framework that can handle DOM manipulation.

    • @mohammedshamil1626
      @mohammedshamil1626 Год назад

      @@DevDrawer Could you please elaborate this answer? I have developed a simple tax calculator app and acheived routing thanks to your tutorials\, but now my Javascript logic for calculations is not working, also cleave.js which I had included to the project is not working too :(

  • @d-a-m-i7439
    @d-a-m-i7439 2 года назад

    wait a min, client side routing is possible with vanilla JS?

    • @DevDrawer
      @DevDrawer  2 года назад

      Yes, but for simple stuff. Having parameters makes it more difficult but even that is possible. Frameworks are better for more complicated setups but it is possible to do it in vanilla 😜

  • @Mobilemaniaplays
    @Mobilemaniaplays Год назад

    What is the name of font you are using in vs code

    • @DevDrawer
      @DevDrawer  Год назад

      I use Fira Code with ligatures.

  • @wutkeks4063
    @wutkeks4063 Месяц назад

    What is that symbol at 14:34?

    • @DevDrawer
      @DevDrawer  Месяц назад

      It is two pipes || (commonly used for OR). Sorry apparently my mouse hovered over it while I was talking.

  • @alditarakez
    @alditarakez 2 года назад

    How to styling ?

    • @DevDrawer
      @DevDrawer  2 года назад

      I'm sorry, I don't understand your question.

  • @danaililiev1404
    @danaililiev1404 28 дней назад

    algorithum hack

    • @DevDrawer
      @DevDrawer  28 дней назад

      I'm sorry but I don't understand what you mean.

  • @chchab
    @chchab 10 месяцев назад

    Your code is very interesting but if the window.location.pathname is like /xx/yy/about it's doesnt work the location.length!=0

    • @DevDrawer
      @DevDrawer  10 месяцев назад

      Maybe I am not understanding your question or that you have location.length != 0, where I have location.length == 0 but I cannot replicate your issue.
      If I go to example.com/xx/yy/about and run window.location.href.length in the console, I get 31 which would be greater than 0 so it would continue to process.
      Having said that, this tutorial is more for simple /pagename sites rather than /x/y/pagename sites. I did not test it for something with 3 sub pages in the URL so the code may not work at all for that type of URL because it was not developed with that in mind. Honestly, I don't know if the code would work with that structure since I did not develop it with that in mind. Your project may be too complicated for how the code currently is. I am sure there can be modifications made to make it work with a deeper link structure, but I don't know just from looking it at currently.