how do you manually add it when the link is www.somesite.com which i would want it to be added to index.html ?

function setActive() {
/*current page function*/
 $('#menu a').each(function(index) {
        if(this.href.trim() == window.location)
            $(this).addClass("current");
    });

this works for any pages that are in the navigation menu.

Dani AI

Generated

— the root URL (http://www.somesite.com or http://www.somesite.com/) does not always match an anchor whose href is index.html. A reliable approach is to compare normalized pathnames (strip query/hash, remove trailing slashes and default filenames like index.html) rather than directly comparing raw href strings or the Location object.

Example (modern browsers):

(function() {
  function normalize(url) {
    var u = new URL(url, location.href);
    var path = u.pathname.replace(/(?:index|default)\.(?:html?|php|aspx?)$/i, '');
    path = path.replace(/\/$/, '');
    return path === '' ? '/' : path;
  }

  var current = normalize(location.href);
  document.querySelectorAll('#menu a').forEach(function(a) {
    var href = a.getAttribute('href') || a.href;
    if (normalize(href) === current) a.classList.add('current');
  });
})();

Notes and alternatives:

  • Use location.href (a string) instead of comparing to the window.location object for clarity.
  • The URL constructor parses relative and absolute hrefs; for very old browsers use an <a> element to parse hrefs as a fallback.
  • If the site uses templates or a server-side framework, adding the active class on the server is more robust than JS.
  • ’s body-class idea is useful for templated sites (server sets a page-specific body class and CSS highlights the right item).
  • ’s suggestion to use the CSS :active pseudo-class is not appropriate for persistent current-page highlighting because :active only applies while the link is being clicked.

This method handles root URLs mapping to index files and ignores query/hash differences, so links like http://www.somesite.com, / and /index.html will all resolve to the same normalized path.

Recommended Answers

All 2 Replies

Why don't you provide a class on the body tag to identify if you are on this page rather than check your current url.

e.g.

<html>
<body class="somesite">
</body>
</html>

and in your javascript you do this

$('#menu a').each(function() {
  if ($('body.somesite').length) {
    $(this).addClass('current');
  }
});
Member Avatar for Member #905211

Why don't you just use the active pseudo class in CSS?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.