Luke Tan Luke Tan - 4 months ago 23
Javascript Question

Simple SPA (Single Page Application) implementation with hash change

I am making an app which lets a user do something on page A. However, I want to include a function which links him to page B, and after completing the activity on B, links him back to A with his page A progress in tact. Currently, after linking to page B and then back to A, all of the progress on page A is gone and back to 0. How would this be accomplished?

Answer

A simple SPA implementation listening to #hash change follows,

$(window).on('hashchange', routePage);

function routePage() {
  var pageName = (window.location.hash) ? window.location.hash : "#page1";
  $('div.pages').hide(); // Hide all pages
  $(pageName).show();    // Show the current page 

  /* switch for page specific functions, not used now */
  switch(pageName) {
    case '#page1':
      alert('Go to Page1');
      break;
    case '#page2':
      alert('Go to Page2');
      break;
  }
}
div.pages *{
  display: block;
  margin: 10px;
}
div.pages a, div.pages h4 {
  padding: 5px;
  text-align: center;
  background: lightgray;
}	
div.pages a{
  text-decoration: none;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- First Page -->
<div id="page1" class="pages">
      <h4>Post your comment</h4>
      <input type="text" name="name" placeholder="Your Name" />
      <textarea name="comments" placeholder="Your comments"></textarea>
      <a href="#page2">Submit</a>
</div>  
<!--Second Page-->
<div id="page2" class="pages" style="display:none;">
      <b>Success!</b>
      <p>Your comments will be published soon...</p>
      <a href="#page1">Edit your comment</a> 
</div>

For detailed SPA implementation using JavaScript frameworks, checkout TodoMVC

http://todomvc.com/