Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In your situation, you could try something like this:</p> <pre><code>$("A").each(function () { if (this.href == document.URL) { $(this).addClass('active'); } }); </code></pre> <p>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.</p> <p>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 <code>http://example.org/dir/</code>, then <code>&lt;a href="index.html"&gt;</code> will not be highlighted, since it resolves to <code>http://example.org/dir/index.html</code>. <code>&lt;a href="/dir/"&gt;</code> will match.<br> (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)</p> <p>The different parts used are:</p> <ul> <li><code>$("A")</code> selects all <code>A</code> elements (anchors). You'll probably want to make it a bit more specific by selecting all <code>A</code> elements within your menu, e.g. <code>$("#menu A")</code>. [jQuery]</li> <li><code>.each(func)</code> executes the specified function on each of selected elements. Within that function <code>this</code> will refer to the selected element. [jQuery]</li> <li><code>this.href</code> returns the <a href="http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-48250443" rel="nofollow noreferrer">absolute URI of the linked resource</a>, not, as you might expect, the possibly relative location specified in the HTML. [standard DOM]</li> <li><code>$(this).addClass(clzName)</code> is used to add a CSS-class to the specified element. [jQuery]</li> </ul> <p>To make sure <code>$("A")</code> finds all elements, execute it after the document is fully loaded (in the <code>$(document).ready()</code> jQuery event-handler, or using the <code>onload</code> attribute of the <code>BODY</code> tag).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload