1

BACKGROUND: I've got a page with the markup shown below. I'm using jQuery's .load() method to replace the contents of div.content-container with this code:

$(document).on('click', 'button#page2', function() {
   $("div.content-container").load("page2.html");
});

QUESTION: The method works, but I'd like to append the URL with a hash, i.e. #page2, which would allow back button functionality. Is there a way to add this feature to a site based entirely on HTML and jQuery .load()?

I've looked at Ben Alman's BBQ plugin, but as someone new to asynchronous content and a non-expert in jQuery, I'm having trouble figuring out how to implement it in my project.

HTML of main page:

<head>
<!--scripts & styles-->
</head>
<body>
<button id="page2">Page 2</button>
<button id="page3">Page 3</button>
<div class="content-container">
<!--content is loaded here-->
</div>
</body>

page2.html (and later pages) are not full HTML documents:

<p>Here's some content from the second page.</p>
Marcatectura
  • 1,721
  • 5
  • 30
  • 49

1 Answers1

2

AFAIK, there is no way to do this withing pure jQuery. You want to manipulate the browser history to add routing to your application, and to do this you require either a jQuery plugin, or directly with the native APIs of the browser: listening to the hashchange event and/or the HTML5 History API.

Quick and dirty toy example to "clear" your div:

$(document).on('click', 'button#page2', function() {
   $("div.content-container").load("page2.html");
   location.hash = '#page2';
});

$(window).on('hashchange', function() {
  if (location.hash === '') {
    $("div.content-container").html('');
  }
});
rvidal
  • 2,012
  • 1
  • 17
  • 24
  • thanks - I can see that's appending the URL. One issue though-hitting the back button doesn't reload the previous page's HTML, it just changes the URL hash. Is this where the HTML5 History API comes in? – Marcatectura Oct 31 '13 at 23:44
  • No. Typically you'll want listen to `hashchange` events and manipulate the DOM accordingly (this is what we're doing in the example, doesn't it get cleared when you hit back?). But beware that this work is *best* left to a library (of course, learning the internals is useful for pedagogical reasons). – rvidal Nov 01 '13 at 00:56