Search code examples
jqueryhtmlhashhashchange

jQuery: hashchange function problems


I've set up a hashchange function on my site, which allows me to switch between 6 different sections on an 'about' page, this works great, it attached the hashes to each section no problem.
The problem I'm having though is when you link to these hashes from another page, they fail to load the relevant content, eg: www.thisisawebsite.com/about/#section03
The hashes works fine when you're on the about page, but coming from anywhere else it just loads section01.

jQuery(document).ready(function(){
jQuery('.about').hide();
jQuery('#section01').show();

jQuery(function(){
jQuery(window).on('hashchange', function(){
        var hash = window.location.hash;
     jQuery('.sub-menu').each(function(){
           jQuery('.about').hide();
         if (jQuery(this).attr('hook') === hash.replace('#section', '')) {
           jQuery('#section'+jQuery(this).attr('hook')).fadeIn();
           return false;
         }
    });  

});
});
jQuery(window).trigger('hashchange');
});

Can this be fixed as the whole idea with me wanting to use a hashchange function was so I didn't have to have 6 separate pages and I could just show / hide each section on one page and link to them with the hashes.


Solution

  • If you load the page with the hash tag already there, does the hashchange event on window even trigger? If it doesn't there's your problem, I'd suggest refactor the each loop out into a separate function, then on document ready just call it to see if any hash tags exist, and then fade in the content.

    Something like this (I haven't tried this because I don't have your DOM, but you'll get the idea.

    jQuery(document).ready(function(){
    
        jQuery(window).on('hashchange', function(){
            var hashFound = determineContent();
            if(hashFound) return false;
        });
    
        function determineContent(){
    
            var hash = window.location.hash;
            jQuery('.about').hide();
    
            jQuery('.sub-menu').each(function(){
    
                 if (jQuery(this).attr('hook') === hash.replace('#section', '')) {
                   jQuery('#section'+jQuery(this).attr('hook')).fadeIn();
                     return true;
                 }
            });
    
            // no hash found, so let's show #section01
            jQuery('#section01').show();
    
            return false;
        }
    
        determineContent();
    });
    

    If this doesn't work, there's a great plugin for just this for jQuery, that handles ajax events as well. I've been using this alot for js based web applications.

    http://www.asual.com/jquery/address/