Question

I'm having trouble getting the jQuery hashchange function to work, it's not something I've ever used before and I can't figure out why it's not working as I want it too.
I have an 'about' page with 6 sections, each of these sections is shown/hidden via a sub-menu, so only one section is shown at a time. But I want to attach hashes to these so they can be linked to from other pages. Here's my code and I'll explain the problem I'm having:

jQuery:

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

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

});
});
$(window).hashchange();
});

HTML:

<div id="content-wrap"> 


    <div id="sub-menu">
        <li id="sub-menu-01" class="sub-menu" hook="01"><a href="#about01">SECTION01</a></li>
        <li id="sub-menu-02" class="sub-menu" hook="02"><a href="#about02">SECTION02</a></li>
        <li id="sub-menu-03" class="sub-menu" hook="03"><a href="#about03">SECTION03</a></li>
        <li id="sub-menu-04" class="sub-menu" hook="04"><a href="#about04">SECTION04</a></li>
        <li id="sub-menu-05" class="sub-menu" hook="05"><a href="#about05">SECTION05</a></li>
        <li id="sub-menu-06" class="sub-menu" hook="06"><a href="#about06">SECTION06</a></li>
    </div>


        <div id="section01" class="about">
CONTENT GOES HERE
        </div>

        <div id="section02" class="about">
CONTENT GOES HERE
        </div>

        <div id="section03" class="about">
CONTENT GOES HERE
        </div>              

        <div id="section04" class="about">
CONTENT GOES HERE
        </div>

        <div id="section05" class="about">
CONTENT GOES HERE
        </div>

        <div id="section06" class="about">
CONTENT GOES HERE
        </div>

</div>

So clicking on the .sub-menu successfully adds the hashes #about01 #about02 etc. But instead of the relevant section being faded in, it just keeps fading in #section01 and I can't understand why.
I had this function working nicely before I introduced hashchange, but now the relevant sections aren't being show, just always #section01 regardless of which .sub-menu you click.

Was it helpful?

Solution

Rather than use .attr hook I would use data-hook and .data. That's not the problem.

You were never actually comparing that the "hook" value matched the hash.

if ($(this).attr('hook') === hash.replace('#about', '')) {

You also need to display the first section if the hash is empty (I suppose), but I'm sure you can figure that out.

http://jsfiddle.net/wkHj2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top