If you find yourself in this scenario, consider implementing the following code snippet:
$("A").each(function () {
if (this.href == document.URL) {
$(this).addClass('active');
}
});
This script checks each link to see if its href attribute matches the current URL of the document. If there is a match, the script adds the 'active' class to that element's CSS classes.
One thing to note is that this method will only be effective if the absolute URLs in the menu and document are identical. For example, if 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
. However,
<a href="/dir/">
will be a match.
(A good practice is to use the same URL for every page on your site for SEO and caching purposes)
The key components utilized in this solution include:
$("A")
selects all anchor elements. It may be beneficial to target specific anchor elements within your menu by using selectors like $("#menu A")
. [jQuery]
.each(func)
runs a specified function for each selected element, with this
referring to the current element. [jQuery]
this.href
retrieves the absolute URI of the linked resource, rather than the potentially relative location as stated in the HTML. [standard DOM]
$(this).addClass(clzName)
adds a CSS class to the specified element. [jQuery]
To ensure that $("A")
captures all elements, execute the script after the entire document has loaded (within the $(document).ready()
jQuery event handler or via the onload
attribute of the BODY
tag).