How to implement routing with a single page application build solely using jQuery

13,772

Solution 1

So, the approach you you need is to listen to hash changes in the url and based on this get the current page and render it in a cointainer. Something like this:

<a href="#page2">Go to Page 2</a>
<div class="page-container"></div>
<script>
$(window).on('hashchange',function(){ 
  var page = window.location.hash;
  $.get('pages/'+page+'.html', function(pageContent){
     $('.page-container').html(pageContent);
  })   
});
</script>

Solution 2

Thank you every one. So I ended up using a combination between @Tulio Faria 's answer and @Gabriele Mantovani.

  • To get the search keyword from url I used window.location.hash
  • To update url used history.pushState({id: 'query'}, '', 'some_url_string');
  • Used $(window).on('hashchange',function(){...}) to load page of the current search keyword if either back or forward buttons of browser were clicked
Share:
13,772
unbalanced_equation
Author by

unbalanced_equation

Updated on June 04, 2022

Comments

  • unbalanced_equation
    unbalanced_equation almost 2 years

    Right now when the user inputs a word in the textfield and hits search, the form submits using $.get(). The data(JSON) is fetched from the server and then the UI is updated.

    What I want to do is pretty simple:

    1) When the form submits, the URL of the browser needs to update (something like search/zyx, zyx is what the user is searching for).

    2) when the page is booked into favorites, or clicked as a link from somewhere the page needs to load and then the textfield value have to be 'zyx'. Also the UI needs to show search result of zyx.

    This is important to my app because I will be using Google Analytics. So the URL is needed to reflect behaviour. Plus the other issue like back button history. Is this possible using just jQuery or some extremely light libraries build on jQuery. I have searched everywhere and all the solutions I found were using MVC frameworks. Or another solution was to use a templating framework like this one. However my app is way too simple for these solutions.

  • unbalanced_equation
    unbalanced_equation over 7 years
    Thanks for your suggestion @llphrin but window.location.replace(url) will cause the page to refresh and that defies the whole purpose of app as being a single page application
  • Crash Override
    Crash Override about 4 years
    this will reload the page