I'm using history.js, and want to call content via ajax when the url changes. I have that working, but the issue is that I need the page to respond differently depending on what URL is loaded when the state changes. For example, within a local scope, I need the pages related to URLs on the right hand nav to load into the content area next to them. If the URL changes to a scope outside of the section I'm in, I want the ajax call to load pages in a container that contains the whole section, including the right hand nav. How can I respond differently to URLs reliably using history.js?
Example:
I have some code that changes the URL when right hand nav items are clicked:
var History = window.History;
$('#right-hand-nav a').on('click', function(event) {
var place = $(this).attr('href');
History.pushState("", "page title", place);
event.preventDefault();
});
...and some code that loads different content when the URL changes:
History.Adapter.bind(window,'statechange',function() {
var State = History.getState()
subContent = $('#sub-content');
$.ajax({
url: State.url,
beforeSend : function() {
// Would start pre-loader code
},
success : function(result) {
// Would end pre-loader code
subContent.html(result);
}
});
});
But, what if I want the onstatechange
event handler to react differently if the new url is outside of this sub-section? What if I want it to replace $('#primary-content').html()
instead of $('#sub-content').html()
if the new URL causes the AJAX request to pull content that doesn't belong in $('#sub-content')
?:
Basic HTML:
<section id="primary-content">
<section id="sub-content">
</section>
<nav id="sub-navigation">
<ul>
<li>
<a href="#">Nav item</a>
</li>
<li>
<a href="#">Nav item</a>
</li>
<li>
<a href="#">Nav item</a>
</li>
</ul>
</nav>
</section>
When URL changes to: www.example.com/sub-section/page.html
<section id="primary-content">
<section id="sub-content">
<!-- ajax should load content here -->
</section>
<nav id="sub-navigation">
<ul>
<li>
<a href="#">Nav item</a>
</li>
<li>
<a href="#">Nav item</a>
</li>
<li>
<a href="#">Nav item</a>
</li>
</ul>
</nav>
</section>
When URL changes to: www.example.com/page.html
<section id="primary-content">
<!-- ajax should load content here -->
</section>
How do you safely determine when the URL goes to a different section using history.js
? How do you react to that change?