Hi, all!

We've all attempted several different ways of highlighting navigation
links which point to the current page. Often times we mark the page
via our PHP by adding a class (e.g. "currentPage") to the navigation
link which points to the current page, or some such. Here's a slightly
different approach...

Today i bought Eric Meyer's CSS book from O'Reilly book
(unfortunately, they only had the German edition :( ) and reading the
section on selectors gave me an idea which i haven't yet seen used in
web design, but which probably does exist out there somewhere: use CSS
to select the current page based off of window.location. AFAIK, only
MSIE has the ability to run javascript from inside the CSS, but a
small bit of jQuery can accomplish the same thing fairly portably...

jQuery(function(){
        var loc = ''+window.location; // Be SURE to force a copy, otherwise
we modify .location next...
        loc = loc.replace( /https?:\/\/[^\/]+/, '' );
// You may want/need to do this:
//      loc = loc.replace( /index.php$/, '' );
//      loc = loc.replace( /index.html$/, '' );
        var sel = '[EMAIL PROTECTED]"'+loc+'"]';
        // alert( sel+"\n"+$(sel)[0].href ); // see below for info
        $(sel).css('background-color','#004040')
                .css('color','#fff')
                .css('font-style', 'italic')
                .css('text-decoration', 'none');
});

Obviously, you may want to expand the selector to only highly this
link inside your navigation menu, and you might even want to disable
the link (set the href to null should do the trick) or replace the A
element with a plain SPAN to make in non-clickable.

There is a bit of trickery to keep in mind here because of how the
href attribute works. If you use $("a...")[0].href you will get a
fully-qualified href, but using $("[EMAIL PROTECTED]'/unqualified/name']") is
needed to select the link - using a fully-qualified href in the
selector will fail unless your links actually are actually fully
qualified (which they normally aren't). You can see this behaviour by
uncommenting the alert() shown above.

This approach might also have an odd side effect due to the stripping
of the domain name from window.location: you might end up marking
external links as the current page, which would obviously be
incorrect. How to generically solve that is left as an exercise for
the reader (and if you do it, please post here so i won't have to
solve the problem myself ;).

Happy hacking!

Reply via email to