Search code examples
jqueryhtmlcssmenuitemmenubar

Navigation without class="current"


I suspect this must be a common practice, but I can't seem to search the right phrase. I'm looking to create a basic html/css navigation menu that styles the current page's button uniquely from the other buttons.

I could obviously use a class such as class="current" on the corresponding buttons. However, I'm hoping to only use one single snippet of code that could be dynamically loaded onto each page (preferably client-side) for easy edits in the future. Is there a common solution to this?

Thanks!

Update: Example code

Current Route:
http://www.example.com/homer.html


HTML

<body class=""> (class added with Javascript)

<ul>
<a href="homer.html"><li>Homer</li></a>
<a href="marge.html"><li>Marge</li></a>
<a href="bart.html"><li>Bart</li></a>
</ul>

</body>

http://jsfiddle.net/daniel_studiolynch/9U6sS/


Solution

  • Here's a pattern I use.

    Set a class on the body tag when the page loads. Use the current route (hash or otherwise).

    // www.yoursite.com/#somehash
    document.body.className = window.location.hash.slice(1); //somehash
    

    Then in your css, use that class to determine an 'active' state.

    .somehash .nav-btn.somehash{...}