views:

69

answers:

2

I've been trying a new way to set up a website using jQuery to dynamically get the content when a link is clicked. Here is the jQuery code:

$(document).ready(function() {

 var content_loader = $('#content-loader');

 $('#nav ul li a').click(function () {
  $(this).closest('ul').find('li.active').removeClass('active');
  $(this).parent().addClass('active');
  content_loader.load('content/' + $(this).attr('data-name') + '.html'); 
  });

 content_loader.load('content/home.html');

});

I've been doing it this way since I have a song in the background of my site that I want to play all the time and not start over every time a link is clicked.

The whole thing works pretty good, except for 2 issues I'm having.

  1. Let's say I click the contact us link. I would now see #contactus at the end of the url. If I then refresh the page, I see my home page content again.
  2. Same problem if I try linking someone to my contact us page.

I was wondering if jQuery can somehow find out what comes after the # sign in the url. In that case, I can change the last line of my jQuery code to load that instead of the home data all the time.

A: 

window.location.hash will contain the value after the hash (if there is one). (This is when there's a hash in the current url, eg. current page, in the browser's address bar.)

Otherwise, if you're reading a link from an href, you'll need to use indexOf('#') and a bit of parsing.

David_001
+1  A: 

Thanks for your answers guys. This is how I did it now:

$(document).ready(function() {

    var content_loader = $('#content-loader');

    $('#nav ul li a').click(function () {
        $(this).closest('ul').find('li.active').removeClass('active');
        $(this).parent().addClass('active');
        content_loader.load('content/' + $(this).attr('href').slice(1) + '.html');  
        });

    var initial = 'home';
    if (window.location.hash) {
        initial = window.location.hash.slice(1);
        }

    $('#nav').find('a[href="#' + initial + '"]').parent('li').addClass('active');
    content_loader.load('content/' + initial + '.html');

    });
Justin