Luke Tan Luke Tan - 1 year ago 110
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 Source

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');
    case '#page2':
      alert('Go to Page2');
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=""></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>
<!--Second Page-->
<div id="page2" class="pages" style="display:none;">
      <p>Your comments will be published soon...</p>
      <a href="#page1">Edit your comment</a> 

For detailed SPA implementation using JavaScript frameworks, checkout TodoMVC

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download