Modifying browser history and url using jQuery

Modifying browser history and url using jQuery

You open a popup and actually want the browser url to reflect the popup/overlay url. You do this for multiple reasons, but mainly for SEO and social media links. It also allows the visitor to use the ‘back’ button and have your page react using AJAX instead of actually reloading the previous page.

Here’s how you do it!

// trigger history update
$('.update-content').click(function() {
  var page_url = $(this).attr('href'); // get url to call
  var page_title = $(this).attr('data-title'); // set data-title in link 
  $.get(page_url, function(data) { // generic ajax call
    $('#content').html(data); // generic html update
    // now time for the good stuff
    if (typeof history.pushState !== "undefined") { // can also use modernizr to check if browser supports history
      var obj = { url: page_url };
      history.pushState(obj, page_title, page_url);
      // obj is used mainly for storage of custom variables
      // page_title is what browser shows in back button
      // page_url is the url the back button goes to
  return false; // since doing ajax

// capture the back button click
$(window).bind('popstate', function(e) {
  var state = e.originalEvent.state;
  if(state) {
    var page_url = state.url; // state is actually 'obj' in previous function
    // run your ajax using page_url as the source url
    $.get(page_url, function(data) { 

Comments are closed.