0

Possible Duplicate:
Making Browser Back button work while using AJAX requests

I want to write some jQuery that when the browser url changes (not refresh) it will do an action.

I will 100% know what the urls will be so they will be

  • www.hello.com/#one
  • www.hello.com/#two
  • www.hello.com/#three

I'm not too concerned about the action (I can sort that); it's more about detecting that the URL has changed when not refreshed.

Any pointers?

I don't want to use a plug-in as I feel they are overkill for what I need, as I know specifics of what I am trying to achieve.

Community
  • 1
  • 1
odd
  • 453
  • 2
  • 10
  • 21

1 Answers1

1

Check out the following code taken from one of my projects (http://yankele.co.il)

$(document).ready(function() {

   //Declare some variables...
   var $mainContent = $('.main-content'),
       contentHeight = $mainContent.height(),
       siteURL = 'http://' + top.location.host.toString(),
       hash = window.location.hash,
       $internalLinks = $('a[href^=' + siteURL + ']'),
       $ajaxSpinner = $('#spinner'),
       URL = '',
       $el;
       console.log(contentHeight);

   $mainContent.height(contentHeight);    
   $internalLinks.each(function() {

      $el = $(this);
      $el.attr('href', '#' + this.pathname);

   }).click(function() {

      $ajaxSpinner.fadeIn();
      $mainContent.animate({opacity: '0.1'});
      $('.current_page_item').removeClass('current_page_item');
      $el = $(this);
      URL = $el.attr('href').substring(1);
      URL += ' #inside';
      $mainContent.load(URL, function() {
         marquee();
         $ajaxSpinner.fadeOut();
         $mainContent.animate({opacity: '1'});
         $el.parent().addClass('current_page_item');
         contentHeight = parseInt($mainContent.css('paddingTop')) + parseInt($mainContent.css('paddingBottom')) + $('#inside').height();
         $mainContent.animate({height: contentHeight});
      });

   });

   if (hash != '' && hash != '#/') {

      $ajaxSpinner.fadeIn();
      $mainContent.animate({opacity: '0.1'});
      $('.current_page_item').removeClass('current_page_item');
      URL = hash.substring(1);
      URL += ' #inside';
      $('a[href="'+window.location.hash+'"]').addClass('current_link').parent().addClass('current_page_item');
      $mainContent.load(URL, function() {
         marquee();
         $ajaxSpinner.fadeOut();
         $mainContent.animate({opacity: '1'});
         contentHeight = parseInt($mainContent.css('paddingTop')) + parseInt($mainContent.css('paddingBottom')) + $('#inside').height();
         $mainContent.animate({height: contentHeight});         
      });

   }

});

It's old, but it works, what it does is, when clicked on any link in the main content area, the main content will fade white, an AJAX spinner will appear, and the page will load the link on AJAX onto the page. It also works when refreshed.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308