We've already made our asynchronous navigation much better than our simple example, but I think we can keep going and make it even better. Next up, we're going to highlight the page currently being viewed in the navigation to make it easy for our site visitors to see which page they're on.
styles.css
again and write a .current
CSS class for the navigation:#ajax-nav li.current{ background:#a3bb00; }
I've made my navigation bar green, so I'm going to make the .current
class a slightly lighter shade of green so that the current item is highlighted in the menu. You can follow my example or create your own style—whatever suits your taste.
.current
class to the current navigation item. We're going to add a few lines to the hashchange
event function we wrote earlier. We'll start by checking to see if there's a hash in the window location:$(document).ready(function(){
$('#ajax-nav a').each(function(){
$(this).attr('href', '#' + $(this).attr('href'));
});
$(window).bind('hashchange', function(e) {
var url = e.fragment;
$('#main-col').load(url + ' #main-col-wrap'),
if (url) {
// The code if there is a hash
} else {
// The code if there is not a hash
}
});
$(window).trigger('hashchange'),
});
$(window).bind('hashchange', function(e) {
var url = e.fragment;
$('#main-col').load(url + ' #main-col-wrap'),
$('#ajax-nav li.current').removeClass('current'),
if (url) {
$('#ajax-nav a[href="#' + url + '"]').parents('li').addClass('current'),
} else {
// The code if there is not a hash
}
});
I'm using jQuery's powerful attribute selectors to select the link with the href
attribute equal to the window's hash. Then I'm using the parents()
method to get the link's parents. I'm passing li
to the parents()
method to tell jQuery I'm only interested in one parent, the <li>
that contains my link. Then I'm using the
addClass()
method to add my current class to the current link.
<li>
and add the current class as shown in the following code:$(window).bind('hashchange', function(e) {
var url = e.fragment;
$('#main-col').load(url + ' #main-col-wrap'),
$('#ajax-nav li.current').removeClass('current'),
if (url) {
$('#ajax-nav a[href="#' + url + '"]').parents('li').addClass('current'),
} else {
$('#ajax-nav li:first-child').addClass('current'),
}
});
$(window).bind('hashchange', function(e) {
var url = e.fragment;
$('#main-col').load(url + ' #main-col-wrap'),
$('#ajax-nav li.current').removeClass('current'),
if (url) {
$('#ajax-nav a[href="#' + url + '"]').parents('li').addClass('current'),
} else {
$('#ajax-nav li:first-child').addClass('current'),
}
});
Refresh the page in the browser and you'll see that the highlight is now working as it should, highlighting only the current page.
What just happened?
We added a few lines of code to our hashchange
function to add a highlight to the current page in the navigation. This will help the site visitor orient themselves on the site and further enforce their current location.
3.17.184.90