I have a navigation area in a separate file from my content, and I pull together the two using a php include. I want the navigation area links to change color based on whatever page is active, i.e. the current URL. So I want jQuery or Javascript to read the current URL (actually just the filename, like home.html), then write CSS based on that.
So like,
if url=home.html, change-css for nav.home.background-> blue
In your situation, you could try something like this:
That checks for every link if the href attribute matches the current documents URL, and if it does add class ‘active’ to the elements CSS classes.
A small caveat: this will only work if the absolute URL referred to in the menu and used in the actual document match exactly.
So let’s say the current URL is
http://example.org/dir/, then<a href="index.html">will not be highlighted, since it resolves tohttp://example.org/dir/index.html.<a href="/dir/">will match.(Making sure the same URL is used for each page throughout the site is good practice anyway, e.g. for search engine optimization and caching proxies)
The different parts used are:
$("A")selects allAelements (anchors). You’ll probably want to make it a bit more specific by selecting allAelements within your menu, e.g.$("#menu A"). [jQuery].each(func)executes the specified function on each of selected elements. Within that functionthiswill refer to the selected element. [jQuery]this.hrefreturns the absolute URI of the linked resource, not, as you might expect, the possibly relative location specified in the HTML. [standard DOM]$(this).addClass(clzName)is used to add a CSS-class to the specified element. [jQuery]To make sure
$("A")finds all elements, execute it after the document is fully loaded (in the$(document).ready()jQuery event-handler, or using theonloadattribute of theBODYtag).