Superfish jquery plugin, highlight selected menu item
I am just wondering what is the more "not hardcoded" approach i can use to make current sele开发者_运维百科cted menu highlighted when using superfish plugin.
For example this one http://hicksdesign.co.uk/journal/highlighting-current-page-with-css looking very "hardcoded way" of doing this.
May be some one may suggest something more smart?
This is how I usually do it - get the current page after the last / in the url and highlight the link that matches it. eg. this page would would return superfish-jquery-plugin-highlight-selected-menu-item
var path = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
$('ul#main-navigation li a[href="' + path + '"]').addClass('active');
Unfortunately, unless you're using a dynamic language to render you pages, it's difficult to provide a neat and tidy solution to this.
One possibility is to use the anchors' href
attribute, which would be equal to part of the window.location.pathname
string.
For instance, assume your site is at the root of a server, with HTML pages called index.html
, work.html
etc. Then, you can grab the pathname
(the part of the URL after the domain name) and match that to the anchor's href
attribute.
Your navigation could look like this:
<nav>
<ul>
<li><a href="index.html">Index</a></li>
<li><a href="work.html">Work</a></li>
<li><a href="projects.html">Projects</a></li>
<li><a href="hobbies.html">Hobbies</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
And your Javascript could look like this:
var pathname = window.location.pathname;
// trim the first slash
var substr = pathname.substr(1);
$('nav').find('li a[href="' + substr + '"]').addClass('current');
So when you're on index.html
, the variable substr
is equal to index.html
, so the list item with data-page-name
equal to index.html
gets the class current
.
This solution is OK in that you only need one navigation tree, as you don't have to edit every page to add an ID or class to an element. You do find yourself in a mess if you change a filename though, because you have to change the data-page-name
attribute in every file (although you'd have to change the anchor href
anyway).
精彩评论