Share |
Posted by Christof On October - 14 - 2010 2 Comments

I was recently asked to set the current page hyperlink (button) active, I did not want to create tons of if/else statements for such a trivial task.

I thought since jQuery had so many powerful selectors and hyperlink (href) selectors as well I could get away with writing a simple jQuery script to do this on-the-fly, as it really only matters to the site visitor and not much to the crawler.

Anyway, I thought I’d share this code with you, here goes…

what happens here is simple, document.location get the current page address that’s being displayed in the browser, we then split this up on the slashes.

We then take the last segment and give it to jQuery as a selector pattern, the .HeaderTopNav is a class wrapper in our html menu and you can leave this out – the $ sign in the pattern means, match at end.

//make sure all links ends with a slash /, else this wont work
var docloc = document.location.toString().split(‘/’);
docloc = docloc[docloc.length-2];
$(‘.HeaderTopNav > a[href$=/'+docloc+'/]‘).css(“border-bottom”,”solid 4px #A2514E”);

If your URL’s don’t end with a slash but perhaps .php, then you would prob do something like this…

var docloc = document.location.toString().split(‘/’);
docloc = docloc[docloc.length-1];
$(‘.HeaderTopNav > a[href$=/'+docloc+']‘).css(“border-bottom”,”solid 4px #A2514E”);

Note: if you copy this code, make sure to replace the WordPress quotes with “real” quotes, Enjoy.

Categories: Web development

2 Responses

  1. Stanley says:

    Awesome code thanks!
    just 1 question how do I focus the parent menu item in a dropdown menu?

    • Christof says:

      Hi Stanley,

      you could obviously use jQuery selectors again to find the child’s parent. Do something like this: $(‘your focused item’).parent(‘.parent css selector’).css(….);

      hope that helps.

Leave a Reply

Featured Posts

How to avoid “spaghetti mess” co..

I believe all programmers found themselves caught in this situation at least once… the dreadful ...

freelance web development vs full-ti..

I quit my full-time job in August 2010 -  I’ve been doing full-time freelance Web ...

Zend Framework vs Codeigniter vs Cak..

There are so many other blogs on this topic and I'm not about to start ...

How to eliminate creative block..

Yet another article on the dreaded phenomena, creative block! I’ve been suffering from this quite a ...

jQuery active link, active page..

I was recently asked to set the current page hyperlink (button) active, I did not ...

Zend Framework new era..

PHP has come a long way over the past decade and is still the most ...

Google interrupts natural progressio..

Is Google (and other SE's) hindering natural technological growth? I think websites would have looked somewhat ...

Magento Pros and Cons..

I've been involved in a 4 month, extensive Magento development, during this time I got ...

Resources