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
It is possible to change the CSS property of an element by using a simple JavaScript API, but we try to complete this challenge using jQuery css() method. Syntax: $().
The jQuery CSS methods allow you to manipulate CSS class or style properties of DOM elements. Use the selector to get the reference of an element(s) and then call jQuery css methods to edit it. Important DOM manipulation methods: css(), addClass(), hasClass(), removeClass(), toggleClass() etc.
Setting individual styles directly from JavaScript is one of the most common scenarios when dealing with dynamic CSS styles. This way allows you to change the CSS styles for one or multiple elements present in the DOM. All you have to do is: Query the element present in the DOM.
cssHooks. Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties.
In your situation, you could try something like this:
$("A").each(function () {
if (this.href == document.URL) {
$(this).addClass('active');
}
});
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 to http://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 all A
elements (anchors). You'll probably want to make it a bit more specific by selecting all A
elements within your menu, e.g. $("#menu A")
. [jQuery].each(func)
executes the specified function on each of selected elements. Within that function this
will refer to the selected element. [jQuery]this.href
returns 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 the onload
attribute of the BODY
tag).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With