0
votes

When we first load the home page, the current menu (home) is highlighted. But when we go to other pages like FAQ, the highlight stays focused on the home menu despite the current class is attributed to the new current menu (faq).

Render

enter image description here

HTML

<div class="main-nav__main-navigation">
   <ul class="main-nav__navigation-box">
     <li>
          <a href="https://example.com">Accueil</a>
     </li>
     <li>
          <a href="https://example.com/services">Services</a>
     </li>
     <li class="current">
          <a href="https://example.com/faq">FAQ</a>
     </li>
     <li>
          <a href="https://example.com/blog">Blog</a>
     </li>
     <li>
          <a href="https://example.com/contact">Contact</a>
     </li>
   </ul>
</div>

CSS

.main-nav__main-navigation .main-nav__navigation-box>li:not(.search-btn).current::before,
.main-nav__main-navigation .main-nav__navigation-box>li:not(.search-btn):hover::before {
    transform: scale(1, 1);
    transform-origin: right center;
}

.main-nav__main-navigation .main-nav__navigation-box>li:not(.search-btn).current::after,
.main-nav__main-navigation .main-nav__navigation-box>li:not(.search-btn):hover::after {
    transform: scale(1, 1);
    transform-origin: right center;
}

.main-nav__main-navigation .main-nav__navigation-box>li.current>a,
.main-nav__main-navigation .main-nav__navigation-box>li:hover>a {
    color: var(--thm-base);
}

JS

function dynamicCurrentMenuClass(selector) {
        let FileName = window.location.href.split('/').reverse()[0];

        selector.find('li').each(function () {
            let anchor = $(this).find('a');
            if ($(anchor).attr('href') == FileName) {
                $(this).addClass('current');
            }
        });
        // if any li has .current elmnt add class
        selector.children('li').each(function () {
            if ($(this).find('.current').length) {
                $(this).addClass('current');
            }
        });
        // if no file name return
        if ('' == FileName) {
            selector.find('li').eq(0).addClass('current');
        }
    }
1

1 Answers

0
votes

I have seen complicated solutions tempting to solve this problem by resetting class or attributing a different active attribut for each page but I have found an easiest solution avoiding you to edit all the files and attributs.

In the case of the FAQ page for example, you just have to add an hashtag next to the address:

<a href="https://example.com/faq/#">FAQ</a>

It solved the problem for me without any further modifications.