STYLE SWITCHER

Dynamically change URL using Push and Popstate

google-https1-ss-1920
This is a simple example using Push and Popstate. This practice is becoming more common throughout sites such as Twitter and Facebook for changing a URL within the address bar without reloading another page. Typically this allows users to bookmark or share URLs when sites are using some type of infinite scroll.
<a href="#" data-location="/inbox/12">Email Item 12</a>
<a href="#" data-location="/inbox/13">Email Item 13</a>
$('a').click(function (e) {
  e.preventDefault();
  // Detect if pushState is available
  if(history.pushState) {
    history.pushState(null, null, $(this).attr('data-location')); // URL is now /inbox/N
    // showMailItem(); // example function to show email based on link clicked
  }
  return false;
});

// Used to detect initial (useless) popstate.
// If history.state exists, assume browser isn't going to fire initial popstate.
var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;

$(window).bind('popstate', function (event) {
  // Ignore inital popstate that some browsers fire on page load
  var initialPop = !popped && location.href == initialURL
  popped = true
  if (initialPop) return;

  // showMailOverview(); // exmaple function to display all email since the user has click Back.

});

Website

Recent Article

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Keep your skills sharp, get informed.

    Subscribe to our mailing list and get interesting stuff and updates to your email inbox